I have to deal with a mssql database and the information given in a table like this:
Users:
ID Name Countries
--------------------
1 User1 1,2,3
2 User2 2,5
Countries:
ID Country
----------
1 Australia
2 Germany
3 USA
4 Norway
5 Canada
Now, what i am looking for is a select statement that will give me a result like this:
Result:
ID User CountriesByName
-----------------------------
1 User1 Australia, Germany, USA
2 User2 Germany, Canada
I’d prefer a solution that won’t depend on special MSSQL syntax over something special, but there is no way for me to use some LINQ-magic 🙁
First, you’ll need to split that string up. Here’s a workable split function:
Then you’ll need to join the values back to your countries table, and re-join them. This will get you most of the way:
However, that leaves a trailing comma. You may want to remove that on some other layer, but just in case you MUST do it in SQL, this should work: