一、SQL Server
方法1:master..spt_values
--最大2047
SELECT number FROM master..spt_values WHERE number>=1 AND number<=100 AND type='P'
方法2:row_number()over()
--最大186
select top 50 row_number() over(order by id) num from sysobjects
方法3:CROSS JOIN
CROSS JOIN
的结果集中数据行的数量是:左表数据行数和右表数据行数的乘积,由于每个TABLE
都有10个数字(从0到9),4个TABLE
进行CROSS JOIN
能够快速产生10的4次方,即10000个顺序数字。
;WITH cte AS (SELECT n FROM(VALUES(0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) AS p(n) )
SELECT a.n+b.n * 10+c.n * 100+d.n * 1000 AS n
FROM cte a
CROSS JOIN cte b
CROSS JOIN cte c
CROSS JOIN cte d
ORDER BY n;
上面实现0-999,下面语句实现1-1000,大同小异:
;WITH cte AS (SELECT n FROM(VALUES(0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) AS p(n) )
SELECT ROW_NUMBER() OVER (ORDER BY(SELECT 1)) id --(SELECT 1)可以替换为NEWID()或a.n
FROM cte a
CROSS APPLY cte b --CROSS APPL可以替换为CROSS JOIN
CROSS APPLY cte c; --CROSS APPL可以替换为CROSS JOIN
方法4:递归
-- 生成连续数值(0-9)
WITH x AS
(SELECT 0 AS id UNION ALL
SELECT id + 1 AS id FROM x WHERE id < 9)
SELECT *FROM x;
-- 生成连续字母(a-z)
WITH x AS
(SELECT 1 AS id UNION ALL
SELECT id + 1 AS id FROM x WHERE id < 26)
SELECT CHAR(id+96) AS id FROM x;
-- 生成连续字符(0-9,a-z)
WITH x AS
(SELECT 0 AS id,CHAR(ascii('0')) AS cc UNION ALL
SELECT id + 1 AS id,CASE WHEN id<9 THEN CHAR(ascii('1')+id) ELSE CHAR(ascii('a')+id-9) END AS cc
FROM x WHERE id < 35)
SELECT id, cc FROM x;
方法5:循环
-- 生成2kw条整数记录
CREATE TABLE dbo.Nums(n INT);
INSERT INTO dbo.Nums VALUES(1);
DECLARE @max AS INT, @rc AS INT;
SET @max = 200000; --数据总数
SET @rc = 1; --插入次数
WHILE @rc <= @max
BEGIN
INSERT INTO dbo.Nums SELECT n + @rc FROM dbo.Nums WHERE n+@rc<=@max;
SET @rc = @rc * 2;
END
-- 具体逻辑理解如下:
-- 第1次插入1条,表数据变为:1 ,2
-- 第2次插入2条,表数据变为:1 ,2 ,3 ,4
-- 第3次插入4条,表数据变为:1 ,2 ,3 ,4 ,5 ,6 ,7 ,8
-- 第4次插入8条,表数据变为:1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,...... ,16
-- ......
-- 第17次插入65536行,表数据变为:1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,...... ,131072
-- 第18次插入剩余的68928行。
二、MySQL
--最大518
SELECT @row:=@row+1 rownum FROM sys.metrics a,(SELECT @row:=0) b