Consider a situation we have two variables in SQL Server 2005’s SP as below,
@string1 = 'a,b,c,d'
@string2 = 'c,d,e,f,g'
Is there a solution to get a new string out of that like (@string1 U @string2) without using any loops. i.e the final string should be like,
@string3 = 'a,b,c,d,e,f,g'
In case you need to do this as a set and not one row at a time. Given the following split function:
Then with the following table and sample data, and string variable, you can get all of the results this way:
Results:
On newer versions (SQL Server 2017+), the query is much simpler, and you don’t need to create your own custom string-splitting function:
Now that all said, what you really should do is follow the previous advice and store these things in a related table in the first place. You can use the same type of splitting methodology to store the strings separately whenever an insert or update happens, instead of just dumping the CSV into a single column, and your applications shouldn’t really have to change the way they’re passing data into your procedures. But it sure will be easier to get the data out!
EDIT
Adding a potential solution for SQL Server 2008 that is a bit more convoluted but gets things done with one less loop (using a massive table scan and replace instead). I don’t think this is any better than the solution above, and it is certainly less maintainable, but it is an option to test out should you find you are able to upgrade to 2008 or better (and also for any 2008+ users who come across this question).
The code:
This is much trickier to do in 2005 (though not impossible) because you need to change the
VALUES()clauses toUNION ALL…