Replace comma separated master data with description in a column

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

There are 2 SQL Server tables:

Products:

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


        
相关标签:
3条回答
  • 2021-01-29 08:22

    You can try this. I used a temporary table but you can use any means you want

    SELECT p.Product , p.Status , s.Description INTO #tmp FROM ( SELECT Name Product, TRIM(value ) Status FROM tblProduct CROSS APPLY STRING_SPLIT(TRIM(StatusCode), ',') ) p JOIN tblStatus s ON s.Code = p.Status

    select distinct Product , stuff(( select ',' + tmp2.Description from #tmp tmp2 where tmp2.Product = tmp1.Product order by tmp2.Product for xml path('') ) ,1,1,'') as StatusCode from #tmp tmp1 group by Product

    0 讨论(0)
  • 2021-01-29 08:27

    Below Query will help to make any comma separated to list.

    SELECT A.OtherID, 
           Split.a.value('.', 'VARCHAR(100)') AS Data
    FROM 
    (
        SELECT OtherID, 
               CAST ('<M>' + REPLACE(Data, ',', '</M><M>') + '</M>' AS XML) AS Data 
        FROM  Table1
    ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
    
    0 讨论(0)
  • 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('<X>'+replace(P.[Status Code],',','</X><X>')+'</X>' 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 
    
    0 讨论(0)
提交回复
热议问题