Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing "1, " and "2, " from a string with out removing "11, " and "12, "

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading