我希望在数据库中有一个带有整数(1,2,...)的单列的表,因为它对某些连接很有帮助。
我想出了一个使用循环的解决方案。有没有更有效的方法来创建这样的表?
我的解决方案
CREATE TABLE #NUM
(
NUM int
)
DECLARE @i int=1
WHILE @i<10000
BEGIN
INSERT INTO #Temp
SELECT @i
SET @i = @i + 1
END
答案 0 :(得分:1)
我将使用计数表
来完成此操作 ;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了解更多信息
答案 1 :(得分:0)
这与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
答案 2 :(得分:0)
SELECT
row_number() over (order by message_id) num
into #Table
from sys.messages