简体   繁体   English

如何从作为参数传递的日期范围中提取星期日

[英]how to extracts sundays from date range passed as parameters

i have two variables passed as parameters to my stored procedure:@fromdate & @tilldate. 我有两个变量作为参数传递给我的存储过程:@fromdate和@tilldate。

I need to extract dates that are on every sundays. 我需要提取每个星期天的日期。

I have been trying for some time but unable to achieve the solution. 我已经尝试了一段时间,但无法实现解决方案。

any help will be appreciated 任何帮助将不胜感激

First, generate a list of dates from @fromDate to @tillDate by using a Tally Table and then get the Sundays by using DATENAME : 首先,生成日期列表@fromDate@tillDate使用帐簿桌使用,然后拿到周日DATENAME

DECLARE @fromDate DATE = '20160301',
        @tillDate DATE = '20160331'

;WITH E1(N) AS(
    SELECT * FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b),
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b),
CteTally(N) AS(
    SELECT TOP (DATEDIFF(DAY, @fromDate, @tillDate) + 1)
        ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
    FROM E4
)
SELECT
    dt = DATEADD(DAY, N - 1, @fromDate)
FROM CteTally
WHERE (DATEPART(dw, DATEADD(DAY, N - 1, @fromDate)) + @@DATEFIRST) % 7 = 1

SQL Fiddle SQL小提琴


(DATEPART(dw, DATEADD(DAY, N - 1, @fromDate)) + @@DATEFIRST) % 7 = 1

Determines if the generated day is a Sunday regardless of the language and @@DATEFIRST setting. 确定生成的日期是否是星期日,而不考虑语言和@@DATEFIRST设置。

; with dates as
(
    select date = @fromdate
    union all
    select date = dateadd(day, 1, date)
    from   dates
    where  date < @tilldate
)
select *
from   dates
where  datename(weekday, date) = 'Sunday'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM