求SQL语句,高手帮忙啊。100分求解谢谢各位大哥!!!
2 a,b 一,二
3 a,b,c 一,二,三
变
1 a 一
2 a 一
2 b 二
3 a 一
3 b 二
3 c 三
题目是这个!!!!谢谢了. 展开
--创建测试数据
select 1 f1,'a' f2,'一' f3 into mytb
union all
select 2,'a,b','一,二'
union all
select 3,'a,b,c','一,二,三,四'
declare @str varchar(8000),
@sqlstr varchar(8000),--动态串
@flag varchar(100),--存放f1
@c2 varchar(1000),--保存f2
@c3 varchar(1000),--保存f3
@i int,@j int
set @sqlstr=''
set @str=''
set @i=1
select @j=max(f1) from mytb
while @i<=@j
begin
select @flag=f1,@c2=f2+',',@c3=f3+',' from mytb where f1=@i
while charindex(',',@c2)>0
begin
set @sqlstr=@sqlstr+' select '+@flag+' f1,'''+left(@c2,charindex(',',@c2)-1)+''' f2,'''+left(@c3,charindex(',',@c2)-1)+''' f3 union all'
set @c2=right(@c2,len(@c2)-charindex(',',@c2))
set @c3=right(@c3,len(@c3)-charindex(',',@c3))
end
set @i=@i+1
end
set @sqlstr=left(@sqlstr,len(@sqlstr)-10)
exec(@sqlstr)
select *
from t1
cross apply dbo.StringSplit(t1.c2,t1.c3)
2009-08-13
select x xx,substr(y,1,1) yy,substr(z,1,1) zz from w
union all
select x xx, substr(y,3,1) yy,substr(z,3,1) zz from w
union all
select x xx, substr(y,5,1) yy,substr(z,5,1) zz from w
order by xx,yy,zz
---
以上,希希望对你有所帮助。