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


 
  
 
  
 
 

你可能感兴趣的:(sql)