How can i find the particular days

半世苍凉 提交于 2019-12-08 04:21:43

问题


I have the date value like this - 12/2011 or 11/2011 (MM/yyyy)

I want to find the sundays on the particular month....

For Example, If i select the month 01/2012, The query should give the result like this

01
08
15
22
29

The above date are sunday.

Expected Output for 01/2012 Month

01
08
15
22
29

How to make a query

Need Query Help


回答1:


With a little help of a number table (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:


Here it comes:

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



回答3:


Edit: use a numbers table in place of the CTE because you are in SQL Server 2000. C'mon, upgrade and do yourself a favour

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



回答4:


You can change date format and use DateName function.

SELECT DateName(dw, GETDATE())



来源:https://stackoverflow.com/questions/8698621/how-can-i-find-the-particular-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!