if object_id('tb') is not null
drop table tb
go
create table tb(name varchar(25))
insert into tb
select 'z,y,w,c' union all
select '1,2,3,4'
select name=substring(a.name,b.number,(charindex(',',a.name+',',b.number))-b.number)
from tb a,master..spt_values b where b.type='p' and b.number between 1 and len(a.name)
and substring(','+a.name,b.number,1)=','
select (charindex(',','z,y,w,c'+',',2))-2
select substring('z,y,w,c',3,(charindex(',','z,y,w,c'+',',3))-3)
select substring(','+'z,y,w,c',2,1)
select * from Tab
--SQL2000用輔助表:
if object_id('Tempdb..#Num') is not null
drop table #Num
go
select top 100 ID=Identity(int,1,1) into #Num from syscolumns a,syscolumns b
Select
a.Col1,COl2=substring(a.Col2,b.ID,charindex(',',a.Col2+',',b.ID)-b.ID)
from
Tab a,#Num b
where
charindex(',',','+a.Col2,b.ID)=b.ID --也可用 substring(','+a.COl2,b.ID,1)=','
--2000不使用輔助表
Select
a.Col1,COl2=substring(a.Col2,b.number,charindex(',',a.Col2+',',b.number)-b.number)
from
Tab a join master..spt_values b
ON B.type='p' AND B.number BETWEEN 1 AND LEN(A.col2)
where
substring(','+a.COl2,b.number,1)=','
select col=substring(a.col2,b.number,)
SQL2005用Xml:
select
a.COl1,b.Col2
from
(select Col1,COl2=convert(xml,'<root><v>'+replace(COl2,',','</v><v>')+'</v></root>') from Tab)a
outer apply
(select Col2=C.v.value('.','nvarchar(100)') from a.COl2.nodes('/root/v')C(v))b
select '<root><v>'+replace(name,',','</v><v>')+'</v></root>' from tb
SQL05用CTE:--此法roy部落格
;with roy as
(select Col1,COl2=cast(left(Col2,charindex(',',Col2+',')-1) as nvarchar(100)),Split=cast(stuff(COl2+',',1,charindex(',',Col2+','),'') as nvarchar(100)) from Tab
union all
select Col1,COl2=cast(left(Split,charindex(',',Split)-1) as nvarchar(100)),Split= cast(stuff(Split,1,charindex(',',Split),'') as nvarchar(100)) from Roy where split>''
)
select COl1,COl2 from roy order by COl1 option (MAXRECURSION 0)
產生結果:
/*
Col1 COl2
----------- -----
1 a
1 b
1 c
2 d
2 e
3 f
*/
原文地址:http://zywsqlserver100.blog.163.com/blog/static/116385209201003011151710/?fromdm&fromSearch&isFromSearchEngine=yes