SQL 用整数创建 table
SQL create table with integers
我想在数据库中有一个 table 单列和整数 (1,2,...) 因为它对某些连接很有帮助。
我想出了一个使用循环的解决方案。有没有更有效的方法来创建这样的 table?
我的解决方案
CREATE TABLE #NUM
(
NUM int
)
DECLARE @i int=1
WHILE @i<10000
BEGIN
INSERT INTO #Temp
SELECT @i
SET @i = @i + 1
END
我会用计数来做到这一点table
;WITH e1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e2 CROSS JOIN e2 AS b) -- 100*100
INSERT INTO #Temp
SELECT ROW_NUMBER() OVER (ORDER BY n) FROM e3 ORDER BY n;
查看here了解更多信息
这个原理和NoDisplayName的回答是一样的,但是我觉得更干净一些(我的意见):
;WITH TBL(ROW_NUM) AS (
SELECT 1 AS ROW_NUM
UNION ALL
SELECT ROW_NUM+1
FROM TBL
WHERE ROW_NUM < 100
)
SELECT ROW_NUMBER() OVER (ORDER BY T1.ROW_NUM) AS ROW_NUM
FROM TBL T1
JOIN TBL T2 ON 1=1
JOIN TBL T3 ON 1=1
SELECT
row_number() over (order by message_id) num
into #Table
from sys.messages
我想在数据库中有一个 table 单列和整数 (1,2,...) 因为它对某些连接很有帮助。
我想出了一个使用循环的解决方案。有没有更有效的方法来创建这样的 table?
我的解决方案
CREATE TABLE #NUM
(
NUM int
)
DECLARE @i int=1
WHILE @i<10000
BEGIN
INSERT INTO #Temp
SELECT @i
SET @i = @i + 1
END
我会用计数来做到这一点table
;WITH e1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e2 CROSS JOIN e2 AS b) -- 100*100
INSERT INTO #Temp
SELECT ROW_NUMBER() OVER (ORDER BY n) FROM e3 ORDER BY n;
查看here了解更多信息
这个原理和NoDisplayName的回答是一样的,但是我觉得更干净一些(我的意见):
;WITH TBL(ROW_NUM) AS (
SELECT 1 AS ROW_NUM
UNION ALL
SELECT ROW_NUM+1
FROM TBL
WHERE ROW_NUM < 100
)
SELECT ROW_NUMBER() OVER (ORDER BY T1.ROW_NUM) AS ROW_NUM
FROM TBL T1
JOIN TBL T2 ON 1=1
JOIN TBL T3 ON 1=1
SELECT
row_number() over (order by message_id) num
into #Table
from sys.messages