I have a column of strings that can contain 1-15 in a comma separated list (e.g. "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15" or "2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15" or "1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15")
How do I remove the "1, " and the "2, " from all examples above?
already tried:
Replace(Replace(@code, "1, ", "")@code, "2, ", "")
Trim(@code)
Initially was thinking to use the replace function but doing so also removes the "1, " and "2, " from "11, " and "12, ".
What are other techniques that can be used here?
>Solution :
The correct thing to do would be to stop using delimited strings.
For more information, Read Is storing a delimited list in a database column really that bad?, where you will see a lot of reasons why the answer to this question is Absolutely yes!
However I know sometimes changing the database structure is impossible even if it is the correct thing to do – so a workaround would be to include the delimiter in the first argument of the replace and then trim it back out.
First, create and populate sample table(Please save us this step in your future questions):
CREATE TABLE TableName (
Id int identity(1,1) ,
DelimitedValues varchar(100)
);
INSERT INTO TableName (DelimitedValues) VALUES
('1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15'),
('2, 3, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15'),
('1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15');
The update statement:
UPDATE TableName
SET DelimitedValues = TRIM(', ' FROM
REPLACE(', '+ DelimitedValues +', ', ', 1, ', ', '))
WHERE Id < 3;
A quick select to make sure the update was successful:
SELECT Id, DelimitedValues
FROM TableName
Results:
| Id | DelimitedValues |
|---|---|
| 1 | 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 |
| 2 | 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 |
| 3 | 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 |
You can see a live demo on db<>fiddle