当前位置: 代码迷 >> Sql Server >> 写一个根据年月自动计算出当月有多少天工作日的自定义函数,只需要考虑周末,不用考虑法定节假日
  详细解决方案

写一个根据年月自动计算出当月有多少天工作日的自定义函数,只需要考虑周末,不用考虑法定节假日

热度:106   发布时间:2016-04-24 08:48:06.0
求助写一个根据年月自动计算出当月有多少天工作日的自定义函数,只需要考虑周末,不用考虑法定节假日
本帖最后由 z418841875 于 2015-09-29 22:02:15 编辑
求助写一个根据年月自动计算出当月有多少天工作日的自定义函数,需要用while循环,只需要考虑周末,不用考虑法定节假日。

如传入‘201509’,算出2015年9月的工作日天数,找了好久都只有根据开始日期和结束日期的
------解决思路----------------------
可以试一下下面的sql

create function [dbo].[func_GetNumOfWorkDays](
@yearMonth varchar(6)
)
returns int
begin
declare @year int=left(@yearMonth,4),         --截取年份
        @month int=right(@yearMonth,2),       --截取月份
        @startDay date='',                    --该月开始日期
        @endDay date='',                      --该月结束日期
        @start int,                           --该月开始日期对应的一周中的第几天(注意星期天对应的是1,而周六对应的是7)
        @end int                              --该月结束日期对应的一周中的第几天(注意星期天对应的是1,而周六对应的是7)
set @startDay=convert(varchar(4),@year)+'-'+convert(varchar(4),@month)+'-01'
if(@month=12)
begin
set @endDay=dateadd(day,-1,convert(varchar(4),@year+1)+'-01-01')
end
else
begin
set @endDay=dateadd(day,-1, convert(varchar(4),@year)+'-'+convert(varchar(4),@month+1)+'-01')
end
set @start=datepart(weekday,@startDay)
set @end=datepart(weekday,@endDay)
if(@start in(1,7))
begin
set @start=2
end
if(@end in(1,7))
begin
set @end=6
end
return (@end-@start+1)%5+20
end

------解决思路----------------------
declare @ym varchar(6)
select @ym='201509'

select COUNT(*) from (
select DATEADD(day, number, convert(datetime, @ym+'01')) allday
from master..spt_values 
where type='p' and number<31
) aa
where DATEPART(weekday, allday) not in (1,7) and DATEPART(MONTH, allday)=CONVERT(int, substring(@ym,5,2))

------解决思路----------------------



declare @month varchar(10) = '201509'
declare @startdate varchar(10)
declare @enddate varchar(10)

set @startdate = STUFF(@month,5,0,'-') + '-01'
set @enddate = convert(varchar(10),DATEADD(month,1,@startdate),121)
select COUNT(*) as '非周末天数'
    -- DATEADD(day, number ,@startdate) 
from master..spt_values 
where type ='p' and number < DATEDIFF(day,@startdate,@enddate)
and  DATEPART(DW, DATEADD(day, number ,@startdate)) not in (7,1)


非周末天数
-----------
22

(1 行受影响)



------解决思路----------------------
-- 参数
DECLARE @ym varchar(6)
SET @ym = '201509'
-- 实现
SET DATEFIRST 1

DECLARE @firstDay datetime
SET @firstDay = CONVERT(datetime,@ym+'01',112)

SELECT COUNT(*) 工作日数
  FROM (
        SELECT DATEADD(day,number,@firstDay) dt
          FROM master..spt_values
         WHERE type = 'p'
           AND number < 31
       ) t
 WHERE month(dt) = month(@firstDay)
   AND DATEPART(weekday,dt) < 6

   工作日数
-----------
         22
  相关解决方案