2012-01-02 132 views
1

我有這樣的日期值 - 12/2011或11/2011(MM/yyyy我如何才能找到特定的日子

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

例如,如果我選擇月01/2012,查詢應該給出這樣的結果

01 
08 
15 
22 
29 

以上日期是星期日。

料到產出01/2012

01 
08 
15 
22 
29 

如何使查詢

需要查詢幫助

+1

你真的儲存月爲 「MM/YYYY」?爲什麼不「yyyymm」更接近ISO並且可排序? – gbn 2012-01-02 08:19:44

回答

4

擁有多臺的幫助不大(master..spt_values

declare @M varchar(7) 
set @M = '01/2012' 

declare @D datetime 
set @D = convert(datetime, '01/'[email protected], 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 
+0

+1我一直在尋找像'master..spt_values'這樣的東西很多次,謝謝:-)。 – 2012-01-02 12:46:24

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'; 
+1

SQL Server 2000中的CTE,我希望:-)。 – 2012-01-02 08:35:19

+0

@MichałPowaga:啊,錯過了。它是2012年,你知道,在SQL Server 2000之後的13年和幾個版本... – gbn 2012-01-02 08:35:56

+0

@gbn在英國文化中它將工作8-),但如果星期日是Воскресение(俄語)或יוםראשון(希伯來語) - 那麼我們有一個問題8-),就像你注意到的那樣。 – 2012-01-02 09:08:57

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 
0

您可以更改日期格式和使用DateName函數。

SELECT DATENAME(DW,GETDATE())

相關問題