我遇到了问题。我想在一个月内使用函数得到星期日,虽然我已经使用一个过程获得了类似的结果,但我需要在我的select查询中调用该函数来返回每个select的结果。我给出了我的程序代码
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
答案 0 :(得分:2)
您当前的问题是您无法从选择中调用存储过程。你需要一个功能。这是一个有效的功能。
另一个问题 - 避免让递归的sql计算一个月内的星期日。这个“简单”的表达式将计算一个月内的星期日。
CREATE function f_count_sundays
(
@Year int,
@Month int
) returns int
BEGIN
DECLARE @x date = dateadd(month,@month-1+(@year-1900)*12,6)
RETURN datediff(d, dateadd(d,datediff(d,-1,@x)/7*7,-1),dateadd(m,1,@x))/7
END
go
SELECT dbo.f_count_sundays(2016,10)
结果:
5
答案 1 :(得分: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)
答案 2 :(得分:0)
select * from f_table_date('20090601', '20090630')
where weekdayname ='sun'
答案 3 :(得分:0)
您是否考虑过创建一个Date表然后再查询,因为这可能是一个比您尝试做的更好的长期解决方案,因为您可以计算一个月中的任何一天,比SQL函数更快,更有说服力
SELECT Count(0)
FROM dimDate
WHERE
DayName = 'Sunday'
AND [CalendarYear] = 2016
AND [CalendarMonth] = 'May'
-- Or you could use a '03' if you preferred.
答案 4 :(得分:-1)
CREATE FUNCTION [DBO].[UDF_getSundaysandSaturdays]
(
@Year int,
@Month int,
@Day int --5 for Sat & 6 for Sun
)
RETURNS INT
as
begin
DECLARE @DayCount 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 @DayCount=(select count(*) from dates where datediff(dd,0,startdate)%7 in (@Day))
RETURN @DayCount
end