2013-01-31 79 views
7

兩個日期日期我想兩個日期CTE TO之間獲得使用SQL Server

之間取缺少的日期說@maxDate=2013-01-28

@curDate= GetDate()

我已經寫CTE做到這一點。這裏是我的CTE:

create procedure EmpDate 
as begin 
declare @curDate Date 
set @curDate = GETDATE() 
declare @maxDate Date 
select @maxDate = MAX(EmpAttendance.Sdate) 
from EmpAttendance 

;with GetDates As 
( 
select 1 as counter, @maxDate as Date 
UNION ALL 
select counter + 1, DATEADD(day,counter,@maxDate) 
from GetDates 
where DATEADD(day, counter, @maxDate) < @curDate 
) 
select Date from GetDates 
end 
go 

這樣做的結果是

Date 
2013-01-28 
2013-01-29 
2013-01-30 

,但我想

2013-01-29 
2013-01-30 

請幫我

在此先感謝

回答

6

變化

select 1 as counter, @maxDate as Date 

select 1 as counter, DATEADD(day,1,@maxDate) as Date 

,使其更簡單,雖然改變CTE

;with GetDates As 
( 
select DATEADD(day,1,@maxDate) as TheDate 
UNION ALL 
select DATEADD(day,1, TheDate) from GetDates 
where TheDate < @curDate 
) 
... 
+0

+1:打我給它。 –

0
DECLARE @STARTDATE  DATETIME; 
DECLARE @ENDDATE  DATETIME; 
DECLARE @STARTYEAR  INTEGER; 
DECLARE @YEARS   INTEGER; 

SET @STARTYEAR = 2017; 
SET @YEARS = 10; 

SELECT @STARTDATE = '20170101'; 
SELECT @ENDDATE = DATEADD(DAY,-1,DATEADD(YEAR,@YEARS,@STARTDATE)); 
DECLARE @FirstDayOfWeek INTEGER; 

SET @FirstDayOfWeek = 6; 

;WITH CTE_DATES 
AS 
(
    SELECT @STARTDATE AS [DATE], 
    1 AS [Level] 
    UNION ALL 
    SELECT 
     DATEADD(DAY,1, [DATE]) , [Level] + 1 
    FROM CTE_DATES 
    WHERE [DATE] < @ENDDATE 
) 
SELECT 
    [DATE], 
    DATENAME(dw,[Date]) AS Daynamelong, 
    LEFT(DATENAME(dw,[Date]),3) AS DaynameShort, 
    DATEPART(dw,[Date]) AS NaturalDayNumber, 
    CASE WHEN DATEPART(dw,[Date]) >= @FirstDayOfWeek THEN (DATEPART(dw,[Date]) - (@FirstDayOfWeek)) +1 
    ELSE 
     ((DATEPART(dw,[Date]) - (@FirstDayOfWeek)) +1) + 7 
    END AS SpecialDayNumber, 
    [Level] 
FROM 
    CTE_DATES 
ORDER BY 
    [DATE] ASC 
OPTION (MAXRECURSION 5000);