SQL 利用游標迴圈新增資料

2021-08-08 18:23:22 字數 2249 閱讀 6853

--查詢資料

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 ''

endas 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

endif @error=0

begin

commit tran --提交

endelse

begin

rollback tran --回滾

endclose y_curr

deallocate y_curr

drop table #t

mysql 儲存過程 利用游標迴圈新增例項

create definer www 192 168 procedure newsng.pro test in params varchar 255 begin declare string varchar 50 declare string1 varchar 50 declare splitcha...

利用游標迴圈遍歷修改列

如下圖,有一張使用者表tb user,現在的需求是將表中所有小於25歲的使用者全部加到25歲 具體 begin declare error int 記錄每次執行sql後是否有錯誤,0表示沒有錯誤 declare temp varchar 50 每次迴圈的物件 可以理解成for迴圈裡面的i值 set ...

sql 游標的使用 游標FOR迴圈小例子

例子 顯示emp表所有雇員名及其工資 複製 如下 declare cursor emp cursor is select ename,sal from emp begin for emp record in emp cursor loop dbms output.put line 姓名 emp re...