SQL 利用遊標循環添加數據

  --查詢數據
  select 
  Invest.UserId,
  BorrowReturn.RealReturnTime,
  Borrow.InvestType,
  case Borrow.InvestType 
  when 0 then '成功000,請注意查收'
  when 1 then '成功111,請注意查收'
  when 2 then '成功222,請注意查收'
  when 4 then '成功444,請注意查收'
  else ''  
  end
  as SiteMessageContent ,
  (BorrowReturnDetail.CaptionMoney+BorrowReturnDetail.InterestMoney+BorrowReturnDetail.SubsidyInterest-BorrowReturnDetail.ReduceManageFee) as BorrowReturnMoney
  into #t --放入臨時表中
  from  BorrowReturn 
  left join BorrowReturnDetail on BorrowReturn.Id=BorrowReturnDetail.BorrowReturnId
  left join Borrow on Borrow.Id=BorrowReturn.BorrowId
  left join Invest on Invest.Id=BorrowReturnDetail.InvestId
  where BorrowReturn.IsDeleted=0 and BorrowReturn.IsSuccess=1 and BorrowReturnDetail.IsDeleted=0




declare @UserId int --臨時變量,用來保存遊標值
declare @SiteMessageContent varchar(500)
declare @RealReturnTime datetime
declare @BorrowReturnMoney decimal(18,2)
DECLARE @error int

set @error=0
BEGIN TRAN --申明事務

declare y_curr cursor for  --申明遊標 

select UserId,SiteMessageContent,RealReturnTime,BorrowReturnMoney from #t


open y_curr
fetch next from y_curr into @UserId,@SiteMessageContent,@RealReturnTime,@BorrowReturnMoney
while @@fetch_status = 0
BEGIN

--查詢顯示
select @UserId,@SiteMessageContent,@RealReturnTime,@BorrowReturnMoney

--理財用戶:添加站內信
insert into SiteMessage (UserId,Title,Content,IsRead,IsDeleted,AddDate) values (@UserId,'理財收益成功',@SiteMessageContent,0,0,@RealReturnTime)

--理財用戶:添加資金流水記錄
insert into CapitalFlow([Money],[Type],Remark,IsDeleted,AddDate,UserId,FlowType) values (@BorrowReturnMoney,5,@SiteMessageContent,0,@RealReturnTime,@UserId,1)


	set @error=@error+@@error--記錄每次運行sql後 是否正確  0正確
	fetch next from y_curr into @UserId,@SiteMessageContent,@RealReturnTime,@BorrowReturnMoney
END
IF @error=0
	BEGIN
		commit tran --提交
	END
ELSE
	BEGIN
		ROLLBACK TRAN --回滾
	END
close y_curr
deallocate y_curr
DROP TABLE #t





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章