最近工作上常常遇到要用Store Procedure的迴圈來解決轉檔問題,
今天忘記加一行而導致鬼擋牆的無限輪迴發生~~~(鬼月不是過了嗎?)
因為寫法和一般java,C等迴圈不太一樣,所以很容易就被忽略,特此趕快做筆記,以防日後
又忘記。
將Content根據'\n'切割,每個切割為一個ROW DATA,
select @Data_ID = '', @Data_ID_VerNo = 0, @Seq_No = 0,@SplitStr=''
declare dataLoop cursor
FOR select Data_ID,Data_ID_VerNo,Rtrim(cast(Content as varchar(500)))+'\n'
from AAAA
open dataLoop
fetch next from dataLoop into @Data_ID,@Data_ID_VerNo,@SplitStr
while(@@fetch_status = 0)
begin
While (Charindex(@SplitChar,@SplitStr)>0)/*切字串成為多個欄位*/
Begin
Insert Into #AAAA (Data)
Select Data = ltrim(rtrim(Substring(@SplitStr,1,Charindex(@SplitChar,@SplitStr)-1)))
Set @SplitStr = Substring(@SplitStr,Charindex(@SplitChar,@SplitStr)+2,len(@SplitStr))
Set @Count = @Count + 1
End
fetch next from dataLoop into @Data_ID,@Data_ID_VerNo,@SplitStr
/*(再加一次fetch next)*/
end
Close dataLoop
Deallocate dataLoop
ltrim(rtrim(Substring(@SplitStr,1,Charindex(@SplitChar,@SplitStr)-1)))利用Charindex來取得'\n'的位置,然後再根據此位置算出的長度用Substring做切割。
Charindex('@SplitChar','@SplitStr')/*Charindex函數*/
Charindex('@STRING','@CHAR')會回傳@CHAR是這個字串的第幾個字元位置。
Substring('@STRING','@START','@LEN')/*Substring函數*/
Substring('@STRING','@START','@LEN')會擷取@STRING從@START且長度@LEN的字串。
沒有留言:
張貼留言