我怎样才能找到特定的日子

时间:2012-01-02 07:59:02

标签: sql sql-server sql-server-2000

我有这样的日期值 - 12/2011或11/2011(MM/yyyy

我想找到特定月份的星期日......

例如,如果我选择月份01/2012,查询应该给出这样的结果

01
08
15
22
29

上述日期是星期日。

01/2012月的预期输出

01
08
15
22
29

如何进行查询

需要查询帮助

4 个答案:

答案 0 :(得分:4)

来了:

SET DATEFIRST 1
DECLARE @givenMonth CHAR(7)
SET @givenMonth = '12/2011'

DECLARE @month INT 
SET @month = CAST(SUBSTRING(@givenMonth, 1, 2) AS INT)
DECLARE @year INT 
SET @year = CAST(SUBSTRING(@givenMonth, 4, 4) AS INT)

DECLARE @Date DATETIME 
SET @Date = DATEADD(month, @month - 1, CAST(CAST(@year AS CHAR(4)) AS DATETIME))
DECLARE @nextMonth DATETIME 
SET @nextMonth = DATEADD(MONTH, 1, @date)

DECLARE @firstSunday DATETIME 
SET @firstSunday = DATEADD(day, 7 - DATEPART(weekday, @date), @date)
CREATE TABLE #Days(Sunday INT)

WHILE @firstSunday < @nextMonth
BEGIN
    INSERT #Days
    SELECT DATEPART(DAY, @firstSunday) Sunday

    SET @firstSunday = DATEADD(day, 7, @firstSunday) 
END
SELECT Sunday
FROM #Days
ORDER BY 1

DROP TABLE #Days

答案 1 :(得分:4)

在数字表(master..spt_values

的帮助下
declare @M varchar(7)
set @M = '01/2012'

declare @D datetime
set @D = convert(datetime, '01/'+@M, 103)

set datefirst 7

select dateadd(day, N.Number, @D)
from master..spt_values as N
where N.type = 'P' and
      dateadd(day, N.Number, @D) >= @D and
      dateadd(day, N.Number, @D) < dateadd(month, 1, @D) and
      datepart(weekday, dateadd(day, N.Number, @D)) = 1

答案 2 :(得分:1)

编辑:使用数字表代替CTE,因为你在SQL Server 2000中。来吧,升级并帮自己一个忙“

DECLARE @monthyear varchar(10) = '11/2012';
DECLARE @start smalldatetime, @end smalldatetime;

-- use yyyymmdd format
SET @start = CAST(RIGHT(@monthyear, 4)+ LEFT(@monthyear, 2) + '01' AS smalldatetime);
-- work backwards from start of next month
SET @end = DATEADD(day, -1, DATEADD(month, 1, @start));

-- recursive CTE. Would be easier with a numbers table
;WITH daycte AS
(
    SELECT @start AS TheDay
    UNION ALL
    SELECT DATEADD(day, 1, TheDay) 
    FROM daycte
    WHERE TheDay < @end
)
SELECT DATENAME(day, TheDay)
FROM daycte 
-- One of many ways. 
-- This is independent of @@datefirst but fails with Chinese and Japanese language settings
WHERE DATENAME(weekday, TheDay) = 'Sunday';

答案 3 :(得分:0)

您可以更改日期格式并使用DateName功能。

SELECT DateName(dw,GETDATE())