Follow the next approach:-
1) Turning a Comma Separated string into individual rows via using CROSS APPLY
with XML
2) Join the two tables with left join.
3) Concatenate many rows with same id via using STUFF
& FOR XML
4) Use Replace function for removing comma.
Demo:-
declare @MyTable table (id int , Tbl1Col varchar(10))
insert into @MyTable values (1,'2'),(2,'2,4'),(3,''),(4,'6'),(5,'3')
declare @MyTable2 table (id int , Tbl2Col varchar(10))
insert into @MyTable2 values (1,'E'),(2,'F'),(3,'M'),(4,'U'),(5,'P'),(6,'C'),(7,'N'),(8,'G')
select a.id , Tbl2Col
into #TestTable
from
(
SELECT A.id,
Split.a.value('.', 'VARCHAR(100)') AS Tbl1Col
FROM
(
SELECT id,
CAST ('<M>' + REPLACE(Tbl1Col, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM @MyTable
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) ) a
left join @MyTable2 b
on a.Tbl1Col = b.id
order by a.id
SELECT id, Tbl2Col =
Replace(STUFF((SELECT DISTINCT ', ' + Tbl2Col
FROM #TestTable b
WHERE b.id = a.id
FOR XML PATH('')), 1, 2, ''),',','')
FROM #TestTable a
GROUP BY id
Output:-
1 F
2 F U
3 NULL
4 C
5 M
References:-
Turning a Comma Separated string into individual rows
How to concatenate many rows with same id in sql?
Finally:-
Don't use this approach, and normalize your database instead , just use it as fun/training/trying .... etc code.