如何使用SQL在2个月后的两个日期之间选择日期

时间:2018-08-07 05:06:06

标签: sql

开始日期-01/01/2018,结束日期:01/10/2018。差异:2个月,

输出:

01/01/2018
01/03/2018
01/05/2018
01/07/2018 

3 个答案:

答案 0 :(得分:1)

尝试使用此查询:

With dt As
 (
 Select @Startdate As [TheDate]
 Union All
 Select DateAdd(month, 2, TheDate) From dt Where [TheDate] < @enddate
 ) 
select [TheDate] from dt

答案 1 :(得分:0)

您可以在下面尝试

CREATE TABLE T(
  ID INT,
  [Start Date Time] DATETIME,
  [End Date Time] DATETIME
);
INSERT INTO T VALUES (1,'2018-01-01 13:00:00.000','2018-10-01 10:00:00.000');


;WITH CTE AS (
    SELECT ID,[Start Date Time] startTime,[End Date Time] endTime
    FROM T
    UNION ALL
    SELECT ID,CAST(CAST(DATEADD(month,2,startTime)AS DATE) AS DATETIME),endTime 
    FROM CTE
    WHERE CAST(CAST(DATEADD(month,2,startTime) AS DATE) AS DATETIME) < endTime
)
SELECT id,
       startTime AS 'Start Date Time',endTime

FROM CTE

http://sqlfiddle.com/#!18/f48ed/1

答案 2 :(得分:0)

尝试这个简单的查询-:

declare @startDate date,@EndDate date;
set @startDate='2018-01-01';
set @EndDate='2018-10-01';
while DATEADD(month,2,@startDate)<@EndDate
begin
print @startDate
set @startDate=DATEADD(month,2,@startDate)
end