1. 程式人生 > >sql server 遊標循環插入數據

sql server 遊標循環插入數據

數據 ror emp rom end 打開 lar mes fetch

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

sql server 遊標循環插入數據