我有带有3条记录的Request表,其结构如下:Id,DateFrom,DateTo
Id DateFrom DateTo
1 15/01/2019 15/01/2019
2 21/01/2019 28/01/2019
3 04/02/2019 09/02/2019
And I want an output like this:
Id Date
1 15/01/2019
2 21/01/2019
2 22/01/2019
2 23/01/2019
2 24/01/2019
2 25/01/2019
2 26/01/2019
2 27/01/2019
2 28/01/2019
3 04/02/2019
3 05/02/2019
3 06/02/2019
3 07/02/2019
3 08/02/2019
3 09/02/2019
我创建了一个表值函数来显示一系列基于日期的DateFrom和DateTo。
CREATE FUNCTION [dbo].[tvfhrms_Calendar_DateRange](@DateFrom date, @DateTo date)
RETURNS @DateOfTheYear Table(Level int,SysDate date)
AS
BEGIN
WITH AllDays
AS (
SELECT [Level] = 1
,[Date] = @DateFrom
UNION ALL
SELECT [Level] = [Level] + 1
,[Date] = DATEADD(DAY, 1, [Date])
FROM AllDays
WHERE [Date] < @DateTo
)
INSERT @DateOfTheYear
SELECT [Level]
,[SysDate]=[Date]
FROM AllDays OPTION (MAXRECURSION 0)
RETURN
END
然后在选择查询中使用
SELECT sysdate from [dbo].[tvfhrms_Calendar_DateRange]('2019-01-10', '2019-02-09')
这将给出Datefrom到DateTo序列的结果。 如何将其集成到表中,以便将输出作为期望值?
答案 0 :(得分:3)
您可以使用APPLY
:
SELECT tt.*
FROM table t CROSS APPLY
(SELECT tt.*
FROM [dbo].[tvfhrms_Calendar_DateRange] (t.datefrom, t.dateto) AS tt
) tt;
答案 1 :(得分:1)
无需额外的带有日期的表格。请注意,我的日期格式不同。
DECLARE @t TABLE (Id INT, DateFrom DATE, DateTo DATE)
INSERT INTO @t VALUES
(1,'01/15/2019','01/15/2019'),
(2,'01/21/2019','01/28/2019'),
(3,'02/04/2019','02/09/2019')
;WITH cte as (
SELECT ID, [Date] = DateFrom FROM @t
UNION ALL
SELECT t.ID, DATEADD(DAY,1,[Date]) FROM @t as t
INNER JOIN cte ON t.ID = cte.ID and cte.[Date] < t.DateTo
)
SELECT * FROM cte
ORDER BY ID