my table1 is :
col1 col2
C1 john
C2 alex
C3 piers
C4 sara
and so table 2:
Here's a way of splitting the data without a function, then using the standard XML PATH method for getting the CSV list:
with CTE as
(
select T2.col1
, T1.col2
from T2
inner join T1 on charindex(',' + T1.col1 + ',', ',' + T2.col2 + ',') > 0
)
select T2.col1
, col2 = stuff(
(
select ',' + CTE.col2
from CTE
where T2.col1 = CTE.col1
for xml path('')
)
, 1
, 1
, ''
)
from T2
SQL Fiddle with demo.
As has been mentioned elsewhere in this question it is hard to query this sort of denormalised data in any sort of efficient manner, so your first priority should be to investigate updating the table structure, but this will at least allow to get the results you require.