下面是完整的解决方案以及您给我的示例数据。
首先,创建一个临时表并用数据填充它。
-- Drop the table
drop table #member;
go
-- Sample table
create table #member
(
member_id int not null,
group_name varchar(256),
member_data varchar(8000)
);
go
-- Sample data
insert into #member values
(1, 'GRP1_ML_Unit1_Role1', 'GRP=User1,DC=com;GRP=User2,DC=com'),
(2, 'GRP2_ML_Unit2_Role2', 'GRP=User3,DC=com;GRP=User4,DC=com;GRP=User5,DC=com'),
(3, 'GRP3_ML_Unit3_Role3', 'GRP=User6,DC=com;GRP=User7,DC=com;GRP=User8,DC=com;GRP=User8,DC=com');
go
-- Show the data
select * from #member;
go
其次,复制那里的众多字符串拆分器之一。我最终为 8K 最大字符串安装了 Jeff Moden 的字符串拆分器。
查询几乎就在那里。但是,我们想要的每一列都是一行。我们需要动态旋转表格。
--
-- Almost there!
--
-- Data in columns, instead of rows
select m.member_id, m.group_name, s.Item as cols_data, 'MEM' + cast(s.ItemNumber as varchar(6)) as cols_name from #member as m
CROSS APPLY dbo.DelimitedSplit8k(m.member_data,';') s
go
最后但并非最不重要的一点是,计算列数。编写动态 TSQL 来旋转我们的数据并获得我们的结果。
--
-- Write dynamic sql to solve
--
DECLARE
@cols AS nvarchar(MAX),
@query AS nvarchar(MAX);
-- Get a dynamic number of columns
SET @cols = STUFF(
(
SELECT distinct ',' + QUOTENAME(c.cols_name)
FROM
(
select m.member_id, m.group_name, s.Item as cols_data, 'MEM' + cast(s.ItemNumber as varchar(6)) as cols_name from #member as m
CROSS APPLY dbo.DelimitedSplit8k(m.member_data,';') s
) as c
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,1,'');
print @cols;
-- Make dynamic pivot query
set @query = 'SELECT member_id as ID1, group_name as GROUP1, ' + @cols + ' from
(
select m.member_id, m.group_name, s.Item as cols_data, ''MEM'' + cast(s.ItemNumber as varchar(6)) as cols_name from #member as m
CROSS APPLY dbo.DelimitedSplit8k(m.member_data, '';'') s
) x
pivot
(
max(cols_data)
for cols_name in (' + @cols + ')
) p ';
execute(@query)
所需格式的结果的屏幕截图。