Replace comma separated master data with description in a column

前端 未结 3 1533
自闭症患者
自闭症患者 2021-01-29 07:48

There are 2 SQL Server tables:

Products:

Name               Status Code
------------------------------------
Product 1          1001, 10         


        
3条回答
  •  北海茫月
    2021-01-29 08:30

    You can use a query like below:

    See working demo

    create table Products (Name varchar(100), [Status Code] varchar(100));
    insert into Products values
    ('Product 1', '1001, 1003')
    ,('Product 2', '1001, 1005, 1006');
    create table [Status] (Code varchar(100),      Description varchar(100));
    insert into [Status] values
    ('1001',   'State A')
    ,('1003',   'State B')
    ,('1005',   'State C')
    ,('1006',   'State D')
    
    ; WITH X AS 
    (
        SELECT 
         P1.Name,
         S.Description
        FROM
         (
         SELECT *,
         cast(''+replace(P.[Status Code],',','')+'' as XML) AS xmlprods FROM Products P
         )P1
         CROSS APPLY
         ( 
         SELECT fdata.D.value('.','varchar(100)') AS splitdata 
         FROM P1.xmlprods.nodes('X') AS fdata(D)) O
         LEFT JOIN [Status] S
         ON S.Code=  LTRIM(RTRIM(O.splitdata ))
        ) 
    
    SELECT 
        Name,
        Description= STUFF((
      SELECT ',' + Description FROM x AS x2 
      WHERE x2.Name = x.Name
      ORDER BY Name FOR XML PATH, 
      TYPE).value(N'.[1]',N'varchar(max)'), 1, 1, '')
      FROM 
      X
    GROUP BY Name 
    

提交回复
热议问题