数据库环境: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]
GO
CREATE PROCEDURE sp_dormLevelMonth
@startDate nvarchar(50),@endDate nvarchar(50),@areaId int,@plateId int
AS
BEGIN
--声明一个游标用来遍历查询到的结果
--起止日期中的所有日期的查询语句
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,
Sex 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.Sex,@nowDate as date from
--入住人数,分男女0
(select COUNT(1) as count,a.Sex,CONVERT(char(10),r.RegistDate,120)date,a.AreaId,a.PlateId,a.DormLevelId
from Register r
left join Apply a on r.ApplyID=a.ApplyId
where a.ApplyType=0
and CONVERT(char(10),r.RegistDate,120)<=@nowDate
and a.AreaId=@areaId and a.PlateId=@plateId
group by a.Sex,CONVERT(char(10),r.RegistDate,120),a.AreaId,a.PlateId,a.DormLevelId) a
left join
--退宿人数,分男女
(select COUNT(1) as count,a.Sex,CONVERT(char(10),r.RegistDate,120)date,a.AreaId,a.PlateId,a.DormLevelId
from Register r
left join Apply a on r.ApplyID=a.ApplyId
where a.ApplyType=1
and CONVERT(char(10),r.RegistDate,120)<=@nowDate
and a.AreaId=@areaId and a.PlateId=@plateId
group by a.Sex,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.Sex=b.Sex
and a.date=b.date
) c
--游标指向下一个
fetch next from myCursor into @nowDate;
END
DECLARE @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
结果: