生成自增值
需求描述
需求:通过SQL生成一个1到1000条记录.
解决方法:通过CTE的递归来实现该需求.
注: 数据库数据集SQL脚本详见如下链接地址
员工表结构和数据初始化SQL脚本
SQL代码
-- SQL Server:
DECLARE @start INT, @end INT
SELECT @start=1, @end=1000
;WITH NumberSequence( Number ) AS
(
SELECT @start AS Num
UNION ALL
SELECT Number + 1
FROM NumberSequence
WHERE Number < @end
)
SELECT * FROM NumberSequence OPTION (MaxRecursion 1000)
执行结果
--Oracle:
WITH t(num) AS (
SELECT 1 FROM DUAL
UNION ALL
SELECT t.num+1
FROM t WHERE t.num<100
)
SELECT * FROM t;
--Mysql(8.0及以上版本):
WITH RECURSIVE cte (num) AS
(
SELECT 1
UNION ALL
SELECT num + 1 FROM cte WHERE num < 100
)
SELECT * FROM cte;