转载

使用CTE生成辅助表(数字或时间)等

数字辅助表:

 

DECLARE @start_digital INT = 0,
        @end_digital INT = 9

;WITH Digital_Rangs(Digital) 
AS
(
    SELECT  @start_digital 
    UNION ALL
    SELECT [Digital] = [Digital] + 1
    FROM [Digital_Rangs]
    WHERE [Digital] < @end_digital
)

SELECT [Digital] FROM [Digital_Rangs] Option (MaxRecursion 0);
Source Code

 

时间辅助表:

 

 

DECLARE @start_date DATE = '2019-05-01',
        @end_date DATE = '2019-05-20'

;WITH [Date_Rangs]([Date]) 
AS
(
    SELECT @start_date 
    UNION ALL
    SELECT [Date] = DATEADD(DAY,1,[Date])
    FROM [Date_Rangs]
    WHERE [Date] < @end_date
)

SELECT [Date] FROM [Date_Rangs] Option (MaxRecursion 0);
Source Code

 

正文到此结束
本文目录