表A
xm xk
张三 语文,历史,音乐
李四 体育,语文
现在想查询得到
xm xk
张三 语文
张三 历史
张三 音乐
李四 体育
李四 语文
1
Select
2 a.xm,xk=substring(a.xk,b.number,charindex(‘,‘,a.xk+‘,‘,b.number)-b.number)
3from4 表A a join master..spt_values b
5ON b.type=‘p‘AND b.numberBETWEEN1ANDLEN(a.xk)
6where7substring(‘,‘+a.xk,b.number,1)=‘,‘
--
1.将字符串转换为列显示
if
object_id(‘tb‘) isnotnulldroptable tb
gocreatetable tb([编号]varchar(3),[产品]varchar(2),[数量]int,[单价]int,[金额]int,[序列号]varchar(8))
insertinto tb([编号],[产品],[数量],[单价],[金额],[序列号])
select‘001‘,‘AA‘,3,5,15,‘12,13,14‘unionallselect‘002‘,‘BB‘,8,9,13,‘22,23,24‘goselect[编号],[产品],[数量],[单价],[金额]
,substring([序列号],b.number,charindex(‘,‘,[序列号]+‘,‘,b.number)-b.number) as[序列号]from tb a with(nolock),master..spt_values b with(nolock)
where b.number>=1and b.number<=len(a.[序列号]) and b.type=‘P‘andsubstring(‘,‘+[序列号],number,1)=‘,‘godroptable tb
go/**
编号 产品 数量 单价 金额 序列号
---- ---- ----------- ----------- ----------- --------
001 AA 3 5 15 12
001 AA 3 5 15 13
001 AA 3 5 15 14
002 BB 8 9 13 22
002 BB 8 9 13 23
002 BB 8 9 13 24
*/----------
--
7.将字符串显示为行列
if
object_id(‘tb‘) isnotnull
droptable tb
createtable tb
(
id intidentity(1,1),
s nvarchar(100)
)
insertinto tb(s) select‘车位地址1,车位状况1|车位地址2,车位状况2|车位地址n,车位状况n‘;
with cte as(
selectsubstring(s,number,charindex(‘|‘,s+‘|‘,number)-number) as ss
from tb with(nolock),master..spt_values with(nolock)
where type=‘P‘andnumber>=1andnumber<=len(s) andsubstring(‘|‘+s,number,1)=‘|‘
)
selectleft(ss,charindex(‘,‘,ss)-1)as s1,substring(ss,charindex(‘,‘,ss)+1,len(ss))as s2 from cte;
droptable tb
/**
s1 s2
----------- ------------
车位地址1 车位状况1
车位地址2 车位状况2
车位地址n 车位状况n
原文:http://www.cnblogs.com/yongtaiyu/p/4795255.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!