SQLServer2008 關於while迴圈

2022-03-09 06:02:39 字數 1287 閱讀 9956

有這樣乙個表tbl

id  code name

11   a      aa/bb/cc

22   b      ee/rr/tt

需要將name段根據『/』拆分開來,變成新的資料行

即:id  code  name

11   a       aa

11   a       bb

......以下省略.....

先給該錶加上序號,存入臨時表

select row_number()over(order by t.code desc) 序號,* into #temp from tbl

--建立乙個帶有固定列的臨時表

create table #temp2

(id int,

code varchar(50),

name varchar(50)

)--使用while迴圈

declare @name varchar(200)

declare @count int

declare @i int

select @count=count(*) from #temp

set @i=1

while(@i<

=@count

)begin

--逐行判斷

select @name=t.name from #temp t where t.序號

=@iwhile(charindex('/',@name,1)!=0)

begin

insert into #temp2 select t.id,t.code,substring(@name,1,charindex('/',@name,1)-1) from #temp t where t.序號

=@iset @name3=substring(@name,charindex('/',@name,1)+1,len(@name)-len(substring(@name,1,charindex('/',@name,1)))) 

endif(charindex('/',@name,1)=0)

begin

insert into #temp2 select t.id,t.code,@name from #temp t where t.序號=@i

endset @i=@i+1

endselect * from #temp2 

注意:

insert into #temp from xx      只能往已經存在的表裡插入值

select * into #temp   可以往未建立的表裡新增值

Sql Server 2008 收縮日誌

收縮日誌 alter database dnname set recovery with no wait goalter database dnname set recovery 簡單模式 gouse dnname godbcc shrinkfile n dnname log 11,truncate...

徹底解除安裝sql server2008

微軟的開發工具在按裝和解除安裝時都讓人頭疼,只能是裝在c盤,裝在其他盤時最容易出事 在重新按裝的時候一定要把以前的例項解除安裝完才行。要不就會出錯。在解除安裝sql server後,其實還沒有完成,還要把登錄檔資訊完全刪乾淨,下面就將教您徹底刪除sql server登錄檔的方法,供您參考。在解除安裝...

SQLServer2008語句查詢

1 判斷資料庫是否存在 if exists select from sys.databases where name 資料庫名 drop database 資料庫名 2 判斷表是否存在 if exists select from sysobjects where id object id 表名 an...