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 =@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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM