列的分拆顯示

來源:互聯網
上載者:User

create table ta(id int, name varchar(50))
insert ta
select 1,           'aa,bb'
union all select 2,           'aaa,bbb,ccc'
union all select 3,           'Aa,Bb,Cc,Dd'

方法1通過遊標實現:

declare @tb table(id int, name varchar(50))--用表變數顯示效果
DECLARE @id int,@name varchar(50)
DECLARE roy CURSOR
FOR SELECT * from ta
OPEN roy
FETCH next FROM roy
into @id,@name
WHILE @@FETCH_STATUS = 0
BEGIN
    while CHARINDEX(',',@name)>0
        begin
            INSERT   @tb  select @id,LEFT(@name,CHARINDEX(',',@name)-1)
            SET      @name=STUFF(@name,1,CHARINDEX(',',@name),'')  
        end
        insert @tb select @id,@name
        FETCH NEXT FROM roy into @id,@name
end
CLOSE roy
DEALLOCATE roy
select * from @tb

方法2用表變數:
declare @ta table(id int)--產生1—50遞增的表變數
declare @i int,@j int
select @i=1,@j=50--定義字元的最大數量
while @i!>@j
    begin
        insert @ta select @i
        select @i=@i+1
    end
select a.id,
      顯示列=substring(a.name,b.id,charindex(',',a.name+',',b.id)-b.id)
from ta a,@ta b
where substring(','+a.name,b.id,1)=','

效果如下:

id          name             
----------- ------------------
1           aa
1           bb
2           aaa
2           bbb
2           ccc
3           Aa
3           Bb
3           Cc
3           Dd

(所影響的行數為 9 行)

--drop table ta

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.