先收藏後細看SQL server語句

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.