创建序列表(整数和日期)

时间:2019-05-17 14:00:23

标签: sql

有时我需要创建定期出现的日期或整数序列表。我手动创建它们,并且可以工作,但是由于存在大量的代码重复,因此维护起来更加困难。说规则间隔出现的整数或日期序列的更可维护的方法是什么?

这是我目前的做法:

DECLARE @IndexDate TABLE (
[Id] INT,
[Date] DATE
)
INSERT INTO @IndexDate (
Id, Date
)
VALUES 
(1, CONCAT(YEAR(GETDATE()), '-01-01')),
(2, CONCAT(YEAR(GETDATE()), '-02-01')),
(3, CONCAT(YEAR(GETDATE()), '-03-01')),
(4, CONCAT(YEAR(GETDATE()), '-04-01')),
(5, CONCAT(YEAR(GETDATE()), '-05-01')),
(6, CONCAT(YEAR(GETDATE()), '-06-01')),
(7, CONCAT(YEAR(GETDATE()), '-07-01')),
(8, CONCAT(YEAR(GETDATE()), '-08-01')),
(9, CONCAT(YEAR(GETDATE()), '-09-01')),
(10, CONCAT(YEAR(GETDATE()), '-10-01')),
(11, CONCAT(YEAR(GETDATE()), '-11-01')),
(12, CONCAT(YEAR(GETDATE()), '-12-01'))

SELECT * FROM @IndexDate

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用递归cte:

WITH cte(n) AS (
   SELECT 1 
   UNION ALL
   SELECT n+ 1 
   FROM cte  
   WHERE n < 12
)
SELECT * 
FROM cte
OPTION (maxrecursion 0);

WITH cte(d) AS (
   SELECT CAST('20190101' AS DATE)
   UNION ALL
   SELECT DATEADD(m, 1, d)
   FROM cte  
   WHERE d < '20200101'
)
SELECT * 
FROM cte
OPTION (maxrecursion 0);

db<>fiddle demo

答案 1 :(得分:1)

要将您的逻辑与递归CTE相匹配,您可以执行以下操作:

with indextable as (
      select 1 as id, datefromparts(year(getdate()), 1, 1) as date
      union all
      select 1 + id, dateadd(month, 1, date)
      from indextable
      where id < 12
     )
select *
from indextable;

一年内,您不必担心option (maxrecursion)

我不太喜欢使用date作为列名,因为它是一个关键字,但是SQL Server允许它。