需求:我有個(gè)存儲(chǔ)過(guò)程,每次執(zhí)行需要帶入一個(gè)連續(xù)的日期。我想遍歷執(zhí)行出一個(gè)月的時(shí)間,怎么搞?
我本來(lái)的想法是:程序里面寫(xiě)一個(gè)for循環(huán),循環(huán)里面循環(huán)傳日期去執(zhí)行這個(gè)存儲(chǔ)過(guò)程。
但是同事告訴我用游標(biāo),我從來(lái)沒(méi)用過(guò),就嘗試了一下,沒(méi)想到成功了哈哈,記錄一下!
— 1.聲明游標(biāo)變量
declare @begin_date varchar(50),
@sumWeight varchar(50)
— 2.聲明游標(biāo)
declare date_cursor cursor for — date_cursor 是游標(biāo)名 ,for 代表做什么
SELECT * FROM (
select convert(varchar(10),dateadd(DAY,t2.number,t1.day),120) day from(select ‘2021-10’+’-01′ day) t1,(select number from MASTER..spt_values WHERE TYPE=’P’ AND number>=0 and number<=31) t2 where convert(varchar(10),dateadd(DAY,t2.number,t1.day),120) like ‘2021-10%’
) T
WHERE T.day >= ‘2021-10-01’ AND T.day <= ‘2021-10-10’
–3.打開(kāi)游標(biāo)
open date_cursor
–4.提取數(shù)據(jù)
fetch next from date_cursor into @begin_date — 將查詢內(nèi)容放入變量中
while @@FETCH_STATUS = 0 — @@FETCH_STATUS 是一個(gè)全局變量,值為0時(shí)表示提取成功,存在數(shù)據(jù), while 循環(huán)表示如果存在數(shù)據(jù)則執(zhí)行
begin
select @sumWeight= sum(NowNum) from MY_SP_LiTiKuDayStock where TIME=”+@begin_date+” –我的業(yè)務(wù)處理
print ‘開(kāi)始時(shí)間:’+@begin_date+’當(dāng)天重量:’+@sumWeight
–print @begin_date
fetch next from date_cursor into @begin_date — 繼續(xù)提取下一行
end
–5.關(guān)閉游標(biāo)
close date_cursor
–6.釋放游標(biāo)
deallocate date_cursor
標(biāo)簽MSSQL,SQLServer,技術(shù)文檔,數(shù)據(jù)庫(kù),SQLSERVER
網(wǎng)友評(píng)論