我的建议是首先规范您的input
表格。在 SQL Server 中,您可以使用递归 CTE 将逗号分隔列表中的数据拆分为行。
CTE 将类似于以下内容:
;with cte (id, col, Name_list, value, text_list) as
(
select id,
cast(left(Name, charindex(',',Name+',')-1) as varchar(50)) col,
stuff(Name, 1, charindex(',',Name+','), '') Name_list,
cast(left(text, charindex(',',text+',')-1) as varchar(50)) value,
stuff(text, 1, charindex(',',text+','), '') text_list
from input
union all
select id,
cast(left(Name_list, charindex(',',Name_list+',')-1) as varchar(50)) col,
stuff(Name_list, 1, charindex(',',Name_list+','), '') Name_list,
cast(left(text_list, charindex(',',text_list+',')-1) as varchar(50)) value,
stuff(text_list, 1, charindex(',',text_list+','), '') text_list
from cte
where Name_list > ''
or text_list > ''
)
select id, col, value
from cte;
请参阅SQL Fiddle with Demo。这将为您提供以下格式的数据:
| ID | COL | VALUE |
-------------------------------
| 1 | Name | John |
| 2 | FirstName | Ray |
| 3 | Name | Mary |
| 4 | FirstName | Cary |
| 5 | PersonID | 1234 |
一旦数据采用该格式,您就可以根据每个表中所需的列来透视数据。
例如,如果您想要数据,Table1
您将使用:
;with cte (id, col, Name_list, value, text_list) as
(
select id,
cast(left(Name, charindex(',',Name+',')-1) as varchar(50)) col,
stuff(Name, 1, charindex(',',Name+','), '') Name_list,
cast(left(text, charindex(',',text+',')-1) as varchar(50)) value,
stuff(text, 1, charindex(',',text+','), '') text_list
from input
union all
select id,
cast(left(Name_list, charindex(',',Name_list+',')-1) as varchar(50)) col,
stuff(Name_list, 1, charindex(',',Name_list+','), '') Name_list,
cast(left(text_list, charindex(',',text_list+',')-1) as varchar(50)) value,
stuff(text_list, 1, charindex(',',text_list+','), '') text_list
from cte
where Name_list > ''
or text_list > ''
)
select *
-- into table1
from
(
select id, col, value
from cte
where col in ('Name', 'DOB')
) d
pivot
(
max(value)
for col in (Name, DOB)
) piv;
请参阅带有演示的 SQL Fiddle
然后,您将使用下一个表的值替换每个查询中的列名。