SqlServer 利用游標批量更新資料

2022-01-10 07:22:12 字數 2839 閱讀 6933

游標在有時候會很有用,在更新一部分不多的資料時,可以很方便的更新資料,不需要再寫乙個小工具來做了,直接寫 sql 就可以了

下面來看乙個實際示例:

-- 宣告字段變數

declare @regioncode int;

declare @regionname nvarchar(64);

declare @provinceid int;

-- 宣告游標

declare provincecursor cursor for(

select id as provinceid, region.regioncode,region.regionname from dbo.provinces as province

join dbo.regions as region on province.name=substring(region.regionname,1, len(province.name)) and region.regiontype=1

);-- 開啟游標

open provincecursor;

-- 移動游標,載入資料

fetch next from provincecursor

into @provinceid,@regioncode,@regionname;

while @@fetch_status = 0

begin

-- 根據游標資料進行操作,這裡只輸出要執行的 sql 指令碼,也可以直接 update,看自己需要

print 'update dbo.provinces set code = ' + convert(nvarchar(12), @regioncode)+', name = n'''+@regionname +''' where id = ' + convert(nvarchar(12), @provinceid) +';';

-- 移動游標到下一條資料

fetch next from provincecursor

into @provinceid,@regioncode,@regionname;

end;

close provincecursor;

deallocate provincecursor;

declare @projectid nvarchar(36)  -- 宣告變數

declare my_cursor cursor --定義游標

for (select originalprojectid from dbo.communityprojects

where communityid = -1) --查出需要的集合放到游標中

open my_cursor; --開啟游標

fetch next from my_cursor into @projectid;

while @@fetch_status = 0

begin

update dbo.communityprojects

set communityid = cast(isnull((

where fangdicommunityid = @projectid

),'-1') as int)

where originalprojectid = @projectid

fetch next from my_cursor into @projectid;

endclose my_cursor; --關閉游標

deallocate my_cursor; --釋放游標

and more

declare @regioncode int;

declare @regionname nvarchar(64);

declare @provinceid int;

declare provincecursor cursor for(

select regioncode,

regionname

from dbo.regions

where regiontype = 1);

open provincecursor;

fetch next from provincecursor

into @regioncode,

@regionname;

while @@fetch_status = 0

begin

set @provinceid =isnull((select id from dbo.provinces where name = @regionname), 0);

if @provinceid > 0

print 'update dbo.provinces set code = ' + convert(nvarchar(12), @regioncode)+' where id = ' + convert(nvarchar(12), @provinceid) +';';

else

print 'insert into dbo.provinces(name,code) values(n''' + @regionname + ''',' + convert(nvarchar(12), @regioncode)+ ');';

fetch next from provincecursor

into @regioncode,

@regionname;

end;

close provincecursor;

deallocate provincecursor;

在做一些小資料量的資料操作時,游標會非常方便,而且游標比較靈活,你可以只生成更新資料的sql,也可以列印出資料更新前後的值,以便錯誤更新資料之後的資料恢復

動態利用游標 實現行轉列

我的工作主要是報表,也沒有邏輯層,全部是靠sql 來實現功能,行轉列,列轉行.現在給大家分享一下,看看有沒有更好的方法啊!alter procedure corss strtabname varchar 50 表名 strcol varchar 50 列名 strgroup varchar 50 分...

利用游標迴圈遍歷修改列

如下圖,有一張使用者表tb user,現在的需求是將表中所有小於25歲的使用者全部加到25歲 具體 begin declare error int 記錄每次執行sql後是否有錯誤,0表示沒有錯誤 declare temp varchar 50 每次迴圈的物件 可以理解成for迴圈裡面的i值 set ...

Oracle使用游標批量更新表資料

oracle使用游標批量更新表資料 begin for jsc in select js.from sf jmmjjs t js,sf ebzcb t cb,sf jmyh t yh where js.yhbh cb.yhbh and js.mjbh cb.mjbh and js.cnq cb.cn...