SQL server使用自定義函數(shù)以及游標(biāo)
| 編號 | 標(biāo)準(zhǔn)宗地編碼(landCode) | 所在區(qū)段編碼(sectCode) | 
| 1 | 131001BG001 | G001 | 
| 2 | 131001BG002 | G001 | 
| 3 | 131001BG003 | G001 | 
| 4 | 131001BG004 | G002 | 
| 5 | 131001BG005 | G003 | 
現(xiàn)在需要將表中的數(shù)據(jù)轉(zhuǎn)換為如下表所示結(jié)果:
| 編號 | 區(qū)段編碼 | 包含的標(biāo)準(zhǔn)宗地 | 
| 1 | G001 | 131001BG001,131001BG002,131001BG003 | 
| 2 | G002 | 131001BG004 | 
| 3 | G003 | 131001BG005 | 
create function combstr(@name nvarchar(50))
returns nvarchar(300)
as
begin
declare @resultStr nvarchar(300)
declare @tempStr nvarchar(500)
declare @flag int
declare myCur cursor --定義游標(biāo)
For(select landCode from land where sectCode=@name )
open myCur –-打開游標(biāo)
fetch next from myCur into tempStr –將游標(biāo)下移
set @flag=0
while @@fetch_status=0
begin
if @flag=0
begin
set @resultStr=@tempStr
end
else
begin
set @resultStr=@resultStr+','+@tempStr
end
set @flag=@flag+1
fetch next from myCur into @tempStr
end
close myCur
deallocate myCur
return @result
end
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
 關(guān)注官方微信
                    關(guān)注官方微信