SQL将2个字段拆分为行

B.H*_*ins 1 sql t-sql sql-server split

我有一行看起来像这样的数据:

200,500,1000 | 50,100,200 | TUA03 | 2019-02-21
Run Code Online (Sandbox Code Playgroud)

从以下查询.

select distinct 
    tbl.qualifier_value,
    tbl.h_discount_val,
    tbl.longlist_mm_text,
    tbl.p_start_date 
from @HoldingTable tbl
Run Code Online (Sandbox Code Playgroud)

我需要将前两个字段拆分为新的相应行.给出以下输出.

200 | 50 | TUA03 | 2019-02-21
500 | 100 | TUA03 | 2019-02-21
1000 | 200 | TUA03 | 2019-02-21
Run Code Online (Sandbox Code Playgroud)

我可以得到第一个字段分割如下:

select distinct 
    s.Item,
    tbl.h_discount_val,
    tbl.longlist_mm_text,
    tbl.p_start_date
from @HoldingTable tbl
outer apply [dbo].[Split](qualifier_value, ',') s
Run Code Online (Sandbox Code Playgroud)

这使:

1000 |  50,100,200 | TUA03 | 2019-02-21
200  |  50,100,200 | TUA03 | 2019-02-21
500  |  50,100,200 | TUA03 | 2019-02-21
Run Code Online (Sandbox Code Playgroud)

我现在还需要拆分第二个字段,但要小心地将位置绑定到第一列的正确位置.通过外部对第二个字段应用相同的想法,我得到9行但是我无法匹配从第一个字段值位置匹配的第二个字段值.

这可以实现吗?

Gor*_*off 5

一种方法是递归CTE.我有点不清楚列名是什么,所以我把它们变成了通用的:

with cte as (
      select left(col1, charindex(',', col1) - 1) as col1,
             left(col2, charindex(',', col2) - 1) as col2,
             col3, col4,
             stuff(col1, 1, charindex(',', col1), '') as col1_rest,
             stuff(col2, 1, charindex(',', col2), '') as col2_rest
      from t
      union all
      select left(col1_rest, charindex(',', col1_rest + ',') - 1) as col1,
             left(col2_rest, charindex(',', col2_rest + ',') - 1) as col2,
             col3, col4,
             stuff(col1_rest, 1, charindex(',', col1_rest + ','), '') as col1_rest,
             stuff(col2_rest, 1, charindex(',', col2_rest + ','), '') as col2_rest
      from cte
      where col1_rest > ''
     )
select col1, col2, col3, col4
from cte;
Run Code Online (Sandbox Code Playgroud)

是一个db <>小提琴.