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 =@sysObjectId)) 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
原文:https://www.cnblogs.com/zhoujiahong/p/9933461.html