获取一年中特定月份的所有星期五日期
问题描述:
嗨
我想在sql server中获取一年中特定月份的所有生日.
请帮我设计一个查询.
Hi
I want to get the all firdays date for a particular month of a year in sql server .
Please help me out to design a query for that.
thanx in advance.
答
第一个问题是每个月的星期五数量在变化.有时您有四个,有时有五个.
一种可能是拥有一个包含所有日期的表,并限制该表中的日期为所需的时间,然后使用 DATEPART [ ^ ]到检查星期几(如果是星期五).像这样的东西:
The first problem is that the amount of Fridays per each month is changing. Sometimes you have four and sometimes five.
One possibility is to have a table which contains all dates and you restrict dates from that table for the desired period and use DATEPART[^] to check the day of the week (if it''s Friday). Something like:
SELECT [Date]
FROM AllDates
WHERE [Date] BETWEEN @start AND @end
AND DATEPART(dw, [Date]) = 6;
另一种方法是使用表值函数来生成行.例如,请参见:在SQL Server中使用表值函数 [
Another way could be using table valued functions to generate the rows. For example see: Using Table-Valued Functions in SQL Server[^]
尝试一下:
Try this :
declare @year int
set @year = 2011
declare @month int
set @month = 12
declare @sd as datetime
declare @fd as datetime
set @sd = CAST(CAST(@year AS varchar) + '-' + CAST(@month AS varchar) + '-1' AS DATETIME)
set @fd = DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, @sd))), DATEADD(MONTH, 1, @sd))
while @sd<=@fd
begin
if datepart(dw, @sd) = 6
print cast (@sd as varchar(max)) + ' is Friday.'
set @sd = DATEADD(DAY, 1, @sd)
end;
祝你好运.
Good Luck.