我需要在给定的日期范围内显示所有星期一的日期。
例如,如果我的开始日期为Canvas
且结束日期为01/05/2015
,则需要显示
31/05/2015
怎么可能?
答案 0 :(得分:6)
此程序独立于地区和语言。
请注意SET DATEFIRST 1
的第一行。
SET DATEFIRST 1; -- First day of the week is set to monday
DECLARE @DateFrom DateTime ='20150601', @DateTo DateTime = '20150630' ;
WITH CTE(dt)
AS
(
SELECT @DateFrom
UNION ALL
SELECT DATEADD(d, 1, dt) FROM CTE
WHERE dt < @DateTo
)
SELECT dt FROM CTE where datepart ("dw", dt) = 1;
答案 1 :(得分:1)
使用CTE可以这样做..
DECLARE @DateFrom DateTime ='2015-05-01',
@DateTo DateTime = '2015-05-31'
;WITH CTE(dt)
AS
(
SELECT @DateFrom
UNION ALL
SELECT DATEADD(d, 1, dt) FROM CTE
WHERE dt < @DateTo
)
SELECT 'Monday', dt FROM CTE
WHERE DATENAME(dw, dt) In ('Monday')
答案 2 :(得分:1)
参考:Select dates of a day between two dates.
SELECT [Day],[Dt] FROM dbo.fnGetDatesforAday('7/1/2008','8/31/2008','Sunday')
CREATE FUNCTION fnGetDatesforAday
(
-- Add the parameters for the function here
@DtFrom DATETIME,
@DtTo DATETIME,
@DayName VARCHAR(12)
)
RETURNS @DateList TABLE ([Day] varchar(20),Dt datetime)
AS
BEGIN
IF NOT (@DayName = 'Monday' OR @DayName = 'Sunday' OR @DayName = 'Tuesday' OR @DayName = 'Wednesday' OR @DayName = 'Thursday' OR @DayName = 'Friday' OR @DayName = 'Saturday')
BEGIN
--Error Insert the error message and return
INSERT INTO @DateList
SELECT 'Invalid Day',NULL AS DAT
RETURN
END
DECLARE @TotDays INT
DECLARE @CNT INT
SET @TotDays = DATEDIFF(DD,@DTFROM,@DTTO)-- [NO OF DAYS between two dates]
SET @CNT = 0
WHILE @TotDays >= @CNT -- repeat for all days
BEGIN
-- Pick each single day and check for the day needed
IF DATENAME(DW, (@DTTO - @CNT)) = @DAYNAME
BEGIN
INSERT INTO @DateList
SELECT @DAYNAME,(@DTTO - @CNT) AS DAT
END
SET @CNT = @CNT + 1
END
RETURN
END
答案 3 :(得分:1)
SET DATEFIRST 7; -- Set's sunday as first day of week, won't work otherwise
DECLARE @StartDate DATE = '06/01/2015'
DECLARE @EndDate DATETIME = '06/30/2015'
DECLARE @TableOfDates TABLE(DateValue DATETIME)
DECLARE @CurrentDate DATETIME
SET @CurrentDate = @startDate
WHILE @CurrentDate <= @endDate
BEGIN
INSERT INTO @TableOfDates(DateValue) VALUES (@CurrentDate)
SET @CurrentDate = DATEADD(DAY, 1, @CurrentDate)
END
SELECT * FROM @TableOfDates WHERE DATEPART(weekday,Datevalue) = 2