小编典典

在函数SQL中获取给定月份的星期日

sql

我正面临一个问题。我想使用一个函数获得一个月中的星期天,尽管我已经使用过程实现了类似的结果,但是我需要在我的选择查询中调用该函数以返回每个选择的结果。我的程序代码已给出

    create proc [dbo].[getSundaysandSaturdays]
(
    @Year int=2016,
    @Month int=11,
    @fdays as int output
)
as
begin
    ;with dates as
    (
        select dateadd(month,@month-1,dateadd(year,@year-1900,0)) as StartDate
        union all
        select startdate + 1 from dates where month(startdate+1) = @Month
    )
    select @fdays=count(*) from dates where datediff(dd,0,startdate)%7 in (4)
    return @fdays
end

阅读 152

收藏
2021-03-17

共1个答案

小编典典

我进行了如下更改,还修改了使用datepart 函数查找星期日所需的逻辑。如果还要返回星期六的计数,则将其添加到where子句中。

 create function [dbo].[getSundaysandSaturdays]
    (
        @Year int,
        @Month int

    ) 
    RETURNS int
    as 
    begin
    declare     @fdays int 
        ;with dates as
        (
            select dateadd(month,@month-1,dateadd(year,@year-1900,0)) as StartDate
            union all
            select startdate + 1 from dates where month(startdate+1) = @Month
        )
        select @fdays=count(*) from dates where datepart(dw,StartDate) =1
      return @fdays
      end

和通话功能如下

  select  dbo.[getSundaysandSaturdays](2015,11)
2021-03-17