需求: 现有一表,如图所示:
要求,将表中的数据按如下格式显示出来:
/*
结果
1 张三 a
2 张三 b
3 张三 c
4 张三 d
5 张三 e
2 李四 a
2 李四 b
2 李四 c
*/
这个问题是在CSDN上找到的,当时,也很郁闷,不过其中有一个牛人用了四种方法写出来了,所以做个笔记。
create table tb(id int,[name] VARCHAR(60),value varchar(30)) insert into tb values(1,'张三','a,b,c,d,e') insert into tb values(2,'李四','a,b,c') GO --1.使用临时表 SELECT TOP 100 id = IDENTITY(int, 1, 1) INTO #tb FROM syscolumns a, syscolumns b SELECT B.id,A.[name], [value]=SUBSTRING(A.[value], B.id, CHARINDEX(',', A.[value] + ',', B.id) - B.id) FROM [tb] A, #tb B WHERE SUBSTRING(',' + A.[value], B.id, 1) = ',' group by [value],[name],B.id --2.不使用临时表 select a.id ,a.[name], value = substring(a.value , b.number , charindex(',' , a.value + ',' , b.number) - b.number) from tb a join master..spt_values b on b.type='p' and b.number between 1 and len(a.value) where substring(',' + a.value , b.number , 1) = ',' --3.使用XML SELECT A.id,A.[name], B.value FROM SELECT id,[name], [value] = CONVERT(xml,'<root><v>' + REPLACE([value], ',', '</v><v>') + '</v></root>') FROM tb ) A OUTER APPLY ( SELECT [value] = N.v.value('.', 'varchar(100)') FROM A.[value].nodes('/root/v') N(v) ) B --4.使用CET ;with tt as ( select id,[name], [value]=cast(left([value],charindex(',',[value]+',')-1) as nvarchar(100)), Split=cast(stuff([value]+',',1,charindex(',',[value]+','),'') as nvarchar(100)) from tb union all select id,[name], [value]=cast(left(Split,charindex(',',Split)-1) as nvarchar(100)), Split= cast(stuff(Split,1,charindex(',',Split),'') as nvarchar(100)) from tt where split>'' ) select id,[name],[value] from tt order by id option (MAXRECURSION 0)
如有好的方法,请大牛继续贴留到恢复贴上。