IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_g_holidays]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_g_holidays]
GO

CREATE proc [dbo].[mps_g_holidays]
@cmpid int,
@year int,
@month int
as
begin
set nocount on
declare @count int
declare @begindate date
declare @enddate date

set @begindate = CONVERT(date,CONVERT(varchar,@year)+'-'+CONVERT(varchar,@month)+'-01')

set @enddate = CONVERT(date,CONVERT(varchar,@year+(@month+1)/13)+'-'+CONVERT(varchar,(@month+1)%13+(@month+1)/13)+'-01')

--判断数据库中是否有当前月份的记录
select @count=count(*) from mps_holidays
where hd_date >= @begindate
and hd_date < @enddate
and hd_cmpid=@cmpid
--如果没有请求的那个月的日期,则创建新数据
if @count = 0
begin
declare @idate date
declare @day int
set @day = 1
set @idate =@begindate
set datefirst 1

begin try
while @idate < @enddate
begin
set @idate = CONVERT(date,CONVERT(varchar,@year)+'-'+CONVERT(varchar,@month)+'-'+CONVERT(varchar,@day))
insert into mps_holidays(hd_cmpid,hd_date,hd_holiday)
values(@cmpid,@idate,case when datepart(weekday, @idate) >5 then 0 else 1 end)
set @day += 1
end
end try
begin catch
set @day = 0
end catch
--
end
--获取最新数据
select * from mps_holidays
where hd_date >= @begindate
and hd_date < @enddate
and hd_cmpid=@cmpid
order by hd_date
end