--创建测试数据
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)
要写一个自定义表值函数,比如命名叫dbo.StringSplit,然后就是:
select *
from t1
cross apply dbo.StringSplit(t1.c2,t1.c3)
有意思 留个记号
有没有达人出现?.....
假如表名为w,表中字段依次为(x,y,z)
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
好像简单的sql办不到,用存储过程吧,因为不知道你的数据库,没办法写到这里(因为不同的数据库语法不一样),看到可以hi我,应该可以帮到你。
---
以上,希希望对你有所帮助。