在不循环SQL的情况下创建行

时间:2017-10-03 15:46:09

标签: sql-server

是否可以在不使用循环函数的情况下创建行?





SQL




  CREATE TABLE #tempTable(id int)
 DECLARE @i int = 0
 DECLARE @numrows int = 5
 WHILE @ i< @ numrows
 BEGIN
 INSERT INTO #tempTable VALUES(@i) 
 SET @i = @ i + 1
 END
 SELECT * FROM#tempTable
  




我可以获得相同的结果没有循环。我正在使用SQL Server 2014




4 个答案:

答案 0 :(得分:1)

请尝试从此处https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1

获取此信息
SELECT TOP (5) n = CONVERT(INT, ROW_NUMBER() OVER (ORDER BY s1.[object_id]))
INTO #tempTable
FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2

SELECT *
FROM #tempTable

答案 1 :(得分:0)

你也可以使用numbers

INSERT INTO #tempTable 
select number from numbers where number<=5

答案 2 :(得分:0)

您可以使用Tally table的概念,可以像下面这样创建

DECLARE @numrows int = 5

select 
 top (select @numrows)
 row_number() over( order by (select 1)) id
from
sys.objects s1 cross join
sys.objects s2

请注意,我们在查询SELECT

中没有使用s1或s1中的任何内容

See working demo

答案 3 :(得分:0)

另一个不涉及从任意表读取数据的选项是使用&#34;数字函数&#34;生成人工行,可以进一步转变为喂养其他表。这样的事情会做:

WITH
L0   AS(SELECT 1 AS c UNION ALL SELECT 1),
L1   AS(SELECT 1 AS c FROM L0 AS A, L0 AS B),
L2   AS(SELECT 1 AS c FROM L1 AS A, L1 AS B),
L3   AS(SELECT 1 AS c FROM L2 AS A, L2 AS B),
L4   AS(SELECT 1 AS c FROM L3 AS A, L3 AS B),
L5   AS(SELECT 1 AS c FROM L4 AS A, L4 AS B),
Nums AS(SELECT ROW_NUMBER() OVER(ORDER BY c) AS n FROM L5)
INSERT INTO #tempTable (id)
SELECT n FROM Nums WHERE n <= @numrows

最初取自http://www.sommarskog.se/arrays-in-sql-2005.html#fn_nums