/*
功能:sql server 2012递归算法应用之02,生成序列(等差数列、字符串序列和日期序列)
作者:felix
日期:20200514
*/
--01生成数值序列,如1-100的公差为1的等差数列
DECLARE @i INT = 1,
@iend INT = 100;
WITH cte_list (i)
AS (SELECT @i AS i
UNION ALL
SELECT i + 1
FROM cte_list--这里自我调用,实现递归。
WHERE i < @iend)
SELECT *
FROM cte_list
OPTION (MAXRECURSION 0);
GO
--02生成字符串序列,如001-100
DECLARE @i INT = 1,
@iend INT = 100;
WITH cte_list (i)
AS (SELECT @i AS i
UNION ALL
SELECT i + 1
FROM cte_list--这里自我调用,实现递归。
WHERE i < @iend)
SELECT RIGHT('00' + CAST(i AS NVARCHAR(3)), 3) AS charlist --一个小小的技巧,需要注意。
FROM cte_list
OPTION (MAXRECURSION 0);
GO
--03生成日期序列,如2020-1-1至2020-12-1
DECLARE @dbegin DATE = '2020-1-1',
@dend DATE = '2020-12-1';
WITH cte_list (ddate)
AS (SELECT @dbegin AS ddate
UNION ALL
SELECT DATEADD(DAY, 1, ddate)
FROM cte_list
WHERE ddate < @dend)
SELECT * --一个小小的技巧,需要注意。
FROM cte_list
OPTION (MAXRECURSION 0);
go 字符串转日期_sql server 2012递归算法应用之02,生成序列(等差数列、字符串序列和日期序列)...
最新推荐文章于 2023-05-26 19:33:43 发布