I am attempting to use the TRANSLATE
function in SQL Server. However, I am receiving an error stating that the second and third arguments of the TRANSLATE
function must contain an equal number of characters.
Query
CREATE TABLE employee
(
EmployeeID INT,
FullName VARCHAR(100) -- Column for Full Name (string)
);
INSERT INTO employee (EmployeeID, FullName)
VALUES (1, 'Stewie Griffin'),
(2, 'Peter B Griffin'),
(3, 'Lois Griffin'),
(4, 'Brian O''Connor'),
(5, 'Meg Griffin');
SELECT
TRANSLATE(FULLNAME,
SUBSTRING(FULLNAME, 2, CHARINDEX(' ', FULLNAME) - 1),
REPLICATE('*', LEN(SUBSTRING(FULLNAME, 2, CHARINDEX(' ', FULLNAME) - 1))))
FROM
employee
Error:
The second and third arguments of the TRANSLATE built-in function must contain an equal number of characters.
Expected Behavior
I expect the query to replace each character in the specified substring with an asterisk (*
) because as I have checked, the second and third arguments seem to be having the same length as each other.
I am attempting to use the TRANSLATE
function in SQL Server. However, I am receiving an error stating that the second and third arguments of the TRANSLATE
function must contain an equal number of characters.
Query
CREATE TABLE employee
(
EmployeeID INT,
FullName VARCHAR(100) -- Column for Full Name (string)
);
INSERT INTO employee (EmployeeID, FullName)
VALUES (1, 'Stewie Griffin'),
(2, 'Peter B Griffin'),
(3, 'Lois Griffin'),
(4, 'Brian O''Connor'),
(5, 'Meg Griffin');
SELECT
TRANSLATE(FULLNAME,
SUBSTRING(FULLNAME, 2, CHARINDEX(' ', FULLNAME) - 1),
REPLICATE('*', LEN(SUBSTRING(FULLNAME, 2, CHARINDEX(' ', FULLNAME) - 1))))
FROM
employee
Error:
The second and third arguments of the TRANSLATE built-in function must contain an equal number of characters.
Expected Behavior
I expect the query to replace each character in the specified substring with an asterisk (*
) because as I have checked, the second and third arguments seem to be having the same length as each other.
1 Answer
Reset to default 2TRANSLATE
replaces all occurrences of the selected chars, as you can see for Brian O'Connor
who becomes B**** O'Co**or
: by including the n
(of Brian) in TRANSLATE()
, you ask it to replace all n
s.
You probably want to replace the found substring instead of any characters found in the substring:
simply cut & paste together: the first letter, the *
s, the last name from the space.
SELECT
SUBSTRING(FULLNAME, 1, 1)
+REPLICATE('*', CHARINDEX(' ', FULLNAME) - 2)
+SUBSTRING(FULLNAME, CHARINDEX(' ', FULLNAME), LEN(FULLNAME) - CHARINDEX(' ', FULLNAME) + 1)
FROM employee;
(no column name) |
---|
S***** Griffin |
P**** B Griffin |
L*** Griffin |
B**** O'Connor |
M** Griffin |
(see it in a fiddle)
SUBSTRING(FULLNAME, 2, CHARINDEX(' ', FULLNAME) - 1)
actually includes the space at the back. Andlen()
does not count the traillling space. Either change to-2
to exclude the trailing space or useDATALENGTH()
– Squirrel Commented Mar 4 at 11:43