无法正确说出问题,因此无法搜索我想要的内容。我需要的只是一个带有一列说guid的虚拟表,我将它用于其他目的。没有实际编写相同的insert .. newID()
n次,想知道是否有一个优雅的解决方案。
类似的问题是如何使用带有1-n数字的int列填充空白表。
Row1: 1
Row2: 2
.......
Row100:100
答案 0 :(得分:3)
你可以递归地做。
对于数字,f.ex。:
WITH r AS (
SELECT 1 AS n
UNION ALL
SELECT n+1 FROM r WHERE n+1<=100
)
SELECT * FROM r
答案 1 :(得分:3)
我建议您使用已知超过100行的任何对象,而不是递归CTE。
--INSERT dbo.newtable(ID, GUID)
SELECT TOP (100) ROW_NUMBER() OVER (ORDER BY [object_id]), NEWID()
FROM sys.all_columns ORDER BY [object_id];
有很多其他想法,请参阅本系列文章:
答案 2 :(得分:1)
单向;
;with guids( i, guid ) as
(
select 1 as i, newid()
union all
select i + 1, newid()
from guids
where i < 100
)
select guid from guids option (maxrecursion 100)
答案 3 :(得分:1)
这种方法非常快。如果你需要从零开始生成一个数字表,它可能是“最好的”可用方法。
WITH
t0(i) AS (SELECT 0 UNION ALL SELECT 0),
t1(i) AS (SELECT 0 FROM t0 a, t0 b),
t2(i) AS (SELECT 0 FROM t1 a, t1 b),
t3(i) AS (SELECT 0 FROM t2 a, t2 b),
n(i) AS (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 0)) FROM t3)
SELECT i FROM n WHERE i BETWEEN 1 AND 100
答案 4 :(得分:0)
只需添加未列出的内容即可
获取10行的快速方法:
SELECT ROW_NUMBER() OVER(
ORDER BY N1.N)
, LOWER(NEWID())
FROM (VALUES(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) AS N1(N) -- 10
如果您希望它基于变量:
DECLARE @N int = 10;
WITH Numbers(number)
AS (SELECT ROW_NUMBER() OVER(
ORDER BY N1.N)
FROM (VALUES(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) AS N1(N) -- 10
CROSS JOIN(VALUES(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) AS N2(N)-- 100
--CROSS JOIN (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS N3 (N) -- 1,000
--CROSS JOIN (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS N4 (N) -- 10,000
--CROSS JOIN (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS N5 (N) -- 100,000
-- Etc....
)
SELECT *
, LOWER(NEWID())
FROM Numbers
WHERE number <= @N;