sql server 游标循环插入数据
Posted zhoujiahong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql server 游标循环插入数据相关的知识,希望对你有一定的参考价值。
begin
declare @temp varchar(50)
declare @error int
set @error = 0
declare @sysObjectId int
set @sysObjectId = 167
declare @count int
select @count=Count(UserId) from (select distinct UserID from HomeSort where UserID not in (select UserID from HomeSort where SysObjectID in (@sysObjectId))) as t
print @count
begin tran
-- 声明游标为UserID
declare HomeSort_cursor cursor
for(select [UserID] from (select distinct UserID from HomeSort where UserID not in (select UserID from HomeSort where SysObjectID [email protected])) as t1)
-- 打开游标
open HomeSort_cursor
-- 开始循环游标变量
fetch next from HomeSort_cursor into @temp
while @@FETCH_STATUS = 0 -- 返回被FETCH语句执行的最后游标的状态
begin
set @error = @error + @@ERROR
insert into HomeSort (SysObjectID, UserID, SortNum) values (@sysObjectId, @temp, 10)
fetch next from HomeSort_cursor into @temp -- 转到下一个游标
end
if @error = 0
begin
print ‘提交成功‘
commit tran -- 提交事务
end
else
begin
print ‘回滚‘
rollback tran -- 回滚事务
end
close HomeSort_cursor -- 关闭游标
deallocate HomeSort_cursor --释放游标
end
以上是关于sql server 游标循环插入数据的主要内容,如果未能解决你的问题,请参考以下文章