Sql server SQL Server:如何将WHILE查询中的SELECT语句输出到一个表中?

Sql server SQL Server:如何将WHILE查询中的SELECT语句输出到一个表中?,sql-server,tsql,Sql Server,Tsql,我使用以下语句: DECLARE @start_date date, @end_date date; SET @start_date = '2016-06-01'; WHILE @start_date < '2017-03-31' BEGIN SET @end_date = DATEADD(day, 6, @start_date); SELECT @start_date AS startDate, @end_date AS endDate SET @start

我使用以下语句:

DECLARE @start_date date, @end_date date;
SET @start_date = '2016-06-01';

WHILE @start_date < '2017-03-31'
BEGIN
    SET @end_date = DATEADD(day, 6, @start_date);

    SELECT @start_date AS startDate, @end_date AS endDate

    SET @start_date = DATEADD(day, 7, @start_date);
END;
我希望输出如下:

+------------+------------+
| startDate  | endDate    |
+------------+------------+
| 2016-06-01 | 2016-06-07 |
+------------+------------+
| 2016-06-08 | 2016-06-14 |
+------------+------------+
如何将结果合并到一个表中,如上所述

谢谢大家!

-- use recursive cte
; with dates as
(
    select @start_date AS startDate, DATEADD(DAY, 6, @start_date) AS endDate
    union all
    select DATEADD(DAY, 7, startDate) AS startDate, DATEADD(DAY, 7, endDate) AS endDate
    from    dates
    where   startDate < '2017-03-31'

)
select  *
from    dates
或者,您也可以使用数字表

如果您想坚持使用WHILE-LOOP的方法,请将日期插入到表变量或temp表中,并在循环后输出

-- use recursive cte
; with dates as
(
    select @start_date AS startDate, DATEADD(DAY, 6, @start_date) AS endDate
    union all
    select DATEADD(DAY, 7, startDate) AS startDate, DATEADD(DAY, 7, endDate) AS endDate
    from    dates
    where   startDate < '2017-03-31'

)
select  *
from    dates