Comma separate value matched on master table

Mohamed Farook 161 Reputation points
2022-12-12T10:43:41.32+00:00

HI,

I need id matched name

create table #master (ID varchar(100),_Name nvarchar(255))
insert into #master (ID,_Name) values ('1001','AAA'),('1002','BBB'),('1003','CCC'),('1004','DDD'),('1005','EEE')

create table #temp1 (ID varchar(100),_Name nvarchar(255))
insert into #temp1 (ID,_Name) values ('1001,1002,1003,1005',''),('1001,1002','')

select * from #temp1

drop table #temp1,#master

Exact output like this

ID _Name
1001,1002,1003,1005 AAA,BBB,CCC,EEE
1001,1002 AAA,BBB

Developer technologies | Transact-SQL
SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-12-12T14:24:38.483+00:00

    Try:

    ;WITH cte AS (SELECT ROW_NUMBER() OVER (ORDER BY _Name) AS RowId, ID, _Name FROM #temp1)  
    ,cte1 AS (SELECT cte.RowID, cte.ID, m._Name, s.value FROM cte CROSS APPLY  STRING_SPLIT(cte.ID, ',') s   
    INNER JOIN #master m ON s.value = m.ID)  
      
    SELECT ID, STRING_AGG(_Name, ',') WITHIN GROUP (ORDER BY _NAME) AS _Name  
    FROM cte1 GROUP BY ID   
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-12-12T14:34:25.527+00:00
    create table #master (ID varchar(100),_Name nvarchar(255))  
    insert into #master (ID,_Name) values ('1001','AAA'),('1002','BBB'),('1003','CCC'),('1004','DDD'),('1005','EEE')  
      
    create table #temp1 (ID varchar(100),_Name nvarchar(255))  
    insert into #temp1 (ID,_Name) values ('1001,1002,1003,1005',''),('1001,1002','')  
    ;with split as  
    (  
    select * from #temp1  
    cross apply string_split(ID,',')  
    )  
    ,mycte as (  
    Select s.ID grp, m.ID,m._Name from split s   
    join #master m on s.value=m.ID  
    )  
      
    select string_agg(ID,',') ID  
    ,string_agg(_Name,',') _Name  
    from mycte  
       
    Group by grp  
      
    drop table #temp1,#master  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.