Here’s what I’m trying to do.
I have these:
Table1:
Name | Surname | Age | Location | ContactPeopleIds
John | Cobaing | 25 | Turkey | 1234,1512,1661, 2366,
Jack | Maltean | 29 | Italy | 6155,2333,1633,
Table2:
ID | Name | LastName | Location
1234 | Meg | Ryan | US
1512 | Jesy | Jade | US
1661 | John | Kradel | US
2366 | Jack | Abdona | Nigeria
TableIWant
Name | Surname | Age | Location | ContactPeopleNames
John | Cobaing | 25 | Turkey | Meg Ryan, Jesy Jade, John Kradel, Jack Abdona
I have found a splitter function called fn_ParseText2Table(data, splitter) that creates a table from the data splitted with splitter char. (Reference here)
For example:
select *
from dbo.fn_ParseText2Table('1234,1512,1661,2366', ',')
function produces:
int_value | num_value | txt_value
null | null | 1234
null | null | 1512
null | null | 1661
null | null | 2366
But I couldn’t create a query using this.
I’m not sure to use t-sql or not.
I’ve tried to use common table expression but couldn’t manage that either.
If you can provide multiple solutions, it would be very kind to provide detail about their performance value differences.
ok…
When you suggested that you’d tried a CTE you where heading in the right direction.
What you need to do however is chain 3 CTE’s together. Once you have the processing chain you then need to progressively pass things through it like a filter, first splitting the ID’s into a column of ints, then joining the ints on table2 to get the names, then recombining those names.
As has been previously mentioned, whoever designed this designed it badly, but assuming your using MS-SQL server and T-SQL the following code will do what you need it to:
It’s probably not as elegant as it could be, and for ease of use you might want to wrap it up in a user defined function and pass the firstname and surname of the person to look up into it. If you do it that way, then you can use the function in a regular SQL select query to return rows direct out of table 1 into a view or another table.
The fun part of it all is actually the way in which we trick SQL server into splitting the string. You’ll notice that we actually replace the ‘,’ with XML tags, then use the XML processing functions to make SQL server think that we are processing an XML string.
SQL Server has had great routines for doing this kind of task sing the 2005 version, and allows for whole blocks of XML to be serialised and de-serialised to/from a varchar field directly in your db table, by making SQL server think it’s dealing with XML it does most of the hard work for us.