儲存過程例項

2021-09-17 08:33:48 字數 2764 閱讀 9242

資料庫環境:sqlserver

概述:查詢某個月份的每天的所有資料,然後存到臨時表裡面,再把臨時表裡面的結果集返回。

-- 判斷要建立的儲存過程名是否存在

if exists (select * from dbo.sysobjects where id =object_id(n'[dbo].[sp_dormlevelmonth]') and objectproperty(id, n'isprocedure')= 1)

-- 刪除儲存過程

drop procedure [dbo].[sp_dormlevelmonth]

gocreate procedure sp_dormlevelmonth

@startdate nvarchar(50),@enddate nvarchar(50),@areaid int,@plateid int

asbegin

--宣告乙個游標用來遍歷查詢到的結果

--起止日期中的所有日期的查詢語句

declare mycursor cursor for select convert(char(10),dateadd(day,number,@startdate),120) allday

from master..spt_values

where type = 'p'

and number <= datediff(day,@startdate,@enddate)

--開啟游標

open mycursor

-- 判斷要建立的表名是否存在

if object_id('tempdb..#dormlevelmonth_') is not null

drop table #dormlevelmonth_

--定義臨時表

create table #dormlevelmonth_

(count int,

areaid int,

dormlevelid int,

plateid int,

*** nvarchar(50),

date nvarchar(50)

)--定義乙個用來獲取游標日期的變數

declare @nowdate nvarchar(50)

--獲取游標指向的資料

fetch next from mycursor into @nowdate;

--使用游標遍歷集合

while @@fetch_status = 0

begin

--定義sql語句

insert into #dormlevelmonth_ select * from

(----合併查詢

select (a.count-isnull(b.count,0)) count,a.areaid,a.dormlevelid,a.plateid,a.***,@nowdate as date from

--入住人數,分男女0

(select count(1) as count,a.***,convert(char(10),r.registdate,120)date,a.areaid,a.plateid,a.dormlevelid

from register r

and convert(char(10),r.registdate,120)<=@nowdate

and a.areaid=@areaid and a.plateid=@plateid

group by a.***,convert(char(10),r.registdate,120),a.areaid,a.plateid,a.dormlevelid) a

left join

--退宿人數,分男女

(select count(1) as count,a.***,convert(char(10),r.registdate,120)date,a.areaid,a.plateid,a.dormlevelid

from register r

and convert(char(10),r.registdate,120)<=@nowdate

and a.areaid=@areaid and a.plateid=@plateid

group by a.***,convert(char(10),r.registdate,120),a.areaid,a.plateid,a.dormlevelid) b

on a.areaid=b.areaid and a.dormlevelid=b.dormlevelid and a.plateid=b.plateid and a.***=b.***

and a.date=b.date

) c--游標指向下乙個

fetch next from mycursor into @nowdate;

enddeclare @sql as varchar(200);

set @sql = 'select * from #dormlevelmonth_';

exec(@sql);

--關閉游標

close mycursor;

--釋放游標

deallocate mycursor;

end

呼叫例項:

--呼叫儲存過程

exec sp_dormlevelmonth '2019-04-01','2019-04-30',1,1

結果:

儲存過程例項

首先查詢,如果有則更新,如果沒有則新增。create proc sp drugstockrecord drugid int,department varchar 500 batchnum varchar 500 amount float,stocktime datetime,producedate ...

儲存過程例項

例1 create proc proc stu sname varchar 20 pwd varchar 20 as select from ren where sname sname and pwd pwd go檢視結果 proc stu admin admin 例2 下面的儲存過程實現使用者驗證...

儲存過程 儲存過程及函式例項

儲存過程及函式例項練習 一 1 建立儲存過程food price count。2 使用call語句來呼叫儲存過程。查詢 在2 18之間的食品種數。3 使用select語句檢視結果。4 使用drop語句刪除儲存過程food price count。可以通過,show procedure status ...