join comma delimited data column

后端 未结 6 1499
日久生厌
日久生厌 2020-11-27 06:30

my table1 is :

T1

col1    col2
 C1     john
 C2     alex
 C3     piers
 C4     sara

and so table 2:

T2

         


        
6条回答
  •  不知归路
    2020-11-27 07:09

    Here's a way of splitting the data without a function, then using the standard XML PATH method for getting the CSV list:

    with CTE as
    (
      select T2.col1
        , T1.col2
      from T2
        inner join T1 on charindex(',' + T1.col1 + ',', ',' + T2.col2 + ',') > 0
    )
    select T2.col1
      , col2 = stuff(
          (
            select ',' + CTE.col2
            from CTE
            where T2.col1 = CTE.col1
            for xml path('')
          )
          , 1
          , 1
          , ''
        )
    from T2
    

    SQL Fiddle with demo.

    As has been mentioned elsewhere in this question it is hard to query this sort of denormalised data in any sort of efficient manner, so your first priority should be to investigate updating the table structure, but this will at least allow to get the results you require.

提交回复
热议问题