SQL生成一年每一天的时间列表的几种方法

工作好几年了,一直没有写博客,准备捡起来。。。
 
以下脚本适用环境:SQL SERVER (starting with 2012)
 
1、构建序列:
 
/*1-1:利用交叉连接,推荐下列这种写法*/
 
SELECT
/*2012 开始已支持OFFSET 语法,不再推荐使用TOP N */
s1.i + s2.i + s3.i + s4.i + s5.i + s6.i + s7.i + s8.i + s9.i AS seq
FROM ( SELECT i = 0 UNION ALL SELECT i = 1 ) s1
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 2 as i) s2
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 4 as i) s3
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 8 as i) s4
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 16 as i) s5
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 32 as i) s6
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 64 as i ) s7
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 128 as i ) s8
CROSS JOIN ( SELECT 0 as i UNION ALL SELECT 256 as i ) s9
ORDER BY seq
OFFSET 0 ROWS FETCH NEXT 366 ROWS ONLY

 

 
/* 1-2:如果系统表列数不够或者过多,会对结果或性能有影响 */
 
SELECT ROW_NUMBER() OVER (ORDER BY a1.object_id) - 1 AS seq
FROM sys.all_columns a1 WITH ( NOLOCK ) ,
sys.all_columns a2 WITH ( NOLOCK )
ORDER BY seq
OFFSET 0 ROWS FETCH NEXT 366 ROWS ONLY

 

 
/* 1-3:循环,不推荐的写法 */
 
DECLARE @I INT

DECLARE @seq TABLE
(
seq INT NOT NULL
)

SET @I=0

WHILE @I < 366
BEGIN

INSERT INTO @seq(seq)
VALUES(@I)

SET @I+=1

END

SELECT * FROM @seq

 

 
 
2、基于以上的任意一种序列,使用DATEADD(DAY,seq,@DstDate) 即可生成一年中的每一天的时间列表。
 
 
3、拓展:MySQL中如何利用以上的思路,在不编写存储过程或函数的前提下,利用SQL 语句拆分一个字符串到数组?
 
点此传送查看答案>>>

转载于:https://www.cnblogs.com/ahleo/p/6763741.html

你可能感兴趣的:(SQL生成一年每一天的时间列表的几种方法)