I have a employee table and the sample data in it is like this. I am using sql server 2008.
CREATE TABLE employee (name nvarchar(255))
insert into employee (name) values ('Alex,AlexMartin'),
('John,John'),
('Mayr,Mayr'),
('Shel,Sheila'),
('corolla,corolla,corolla3'),
('Mary4,Mary,Mary'),
('Justin,Justin,Justin'),
('Sara,Sara,Sara,Sara'),
('clarence,clarence,clarence458,clarence,clarence'),
('fiesta,fiesta,fiesta,fiesta,fiesta'),
('scorpio1,scorpio,scorpio,scorpio4,scorpio')
I want to delete a value if all the values in the string are same example: John,John should be replaced by ‘John’. If all the names in string are not equal like Shel,Sheila it should retain both the values.
For this I am using
but it is changing
update employee set name=(select PARSENAME(REPLACE(name, ',', '.'), 2)) where (select PARSENAME(REPLACE(name, ',', '.'), 2))
like (select PARSENAME(REPLACE(name, ',', '.'), 1))Mary4,Mary,Mary to Mary. I tried combinations for 5, 4, and 3 names but there is no use. In fact for five names this code is not at all working. Is there any efficient way to do this?
This will get the data in the format you’re looking for:
It works by getting the first name in the comma-separated list. By your requirements all of the items have to be identical in order to condense the list, so it doesn’t matter which element in the list we use for comparison.
All occurrences of the first item are removed from the list. Then all of the commas are removed. If the resulting value is empty (i.e.
'') then we know all of the items are identical. In that case the first element is used as theResultvalue. Otherwise, we return the original list unchanged.EDIT: Some of your data mustn’t have a
,in it, so I’ve updated the answer to take care of that. It will just return the same input if a delimiter doesn’t exist.