I have table employee_table which is like this
org employeeid (int) firstname lastname
1234 56788934 Suresh Raina
1234 56793904 Virat Kohli
then i have project_table which is like this
Project members (varchar)
A123 56788934,56793900
Now i need to fetch corresponding names of employees and stuff in a single row like this.
Project members (varchar)
A123 Suresh Raina, Virat Kohli
I have written below query which is not working. please help.
SELECT project,
(
SELECT message_text = Stuff(
(
SELECT ', ' + Concat(firstname,' ',lastname)
FROM employee_table t1
WHERE t1.org = t2.org
AND CONVERT(VARCHAR,t1.userid) IN (Concat('''',Replace(pt.members,',',''','''),'''')) --adding single quotes at start and end of each number
FOR xml path ('')) , 1, 1, '')
FROM employee_table t2
WHERE t2.userid IN
group BY org;) FROM project_table pt
Here is a solution for SQL Server 2017 onwards.
It is using a pair of handy functions available in SQL Server 2017:
STRING_SPLIT()
STRING_AGG()
Method #2 covers solution for SQL Server 2008 onwards.
SQL
Output