对于两个日期之间的每一天,在开始/结束列中添加一行具有相同信息但只有那一天

2022-01-09 00:00:00 datetime sql insert sql-server

我有一张表,类型为 varchardatetimedatetime:

I have a table, with types varchar, datetime, datetime:

NAME | START | END
Bob  | 10/30 | 11/2

我可以查找什么 SQL 查询来了解如何制作该表?:

What's a SQL query can I look up to find out how to make that table be?:

NAME | START | END
Bob  | 10/30 | 10/30
Bob  | 10/31 | 10/31
Bob  | 11/01 | 11/01
Bob  | 11/02 | 11/02

这只运行一次,并且在一个非常小的数据集上.不需要优化.

This is only ran once, and on a very small dataset. Optimization isn't necessary.

推荐答案

可能你需要一个Recursive CTE.

CREATE TABLE #dates(NAME  VARCHAR(50),START DATETIME,[END] DATETIME)

INSERT INTO #dates
VALUES      ('Bob','2014-10-30','2014-11-02')

DECLARE @maxdate DATETIME = (SELECT Max([end]) FROM   #dates);

WITH cte
     AS (SELECT NAME,
                START,
                [END]
         FROM   #dates
         UNION ALL
         SELECT NAME,
                Dateadd(day, 1, start),
                Dateadd(day, 1, start)
         FROM   cte
         WHERE  start < @maxdate)
SELECT *
FROM   cte 

输出:

name    START       END
----    ----------  ----------
Bob     2014-10-30  2014-10-30
Bob     2014-10-31  2014-10-31
Bob     2014-11-01  2014-11-01
Bob     2014-11-02  2014-11-02

相关文章