SQL Server How can INSERT INTO a table 300 times within a loop in SQL?

bpsygsoo  于 2023-05-05  发布在  其他
关注(0)|答案(5)|浏览(171)

I would like to insert a value retrieved from a counter in SQL and repeat it 300 times.

Something like:

DECLARE @Counter = 0;

-- BEGIN Loop 
    SET @Counter = @Counter + 1 
    INSERT INTO tblFoo VALUES(@Counter)
-- REPEAT 300 times

How can I achieve this? Thanks

cbwuti44

cbwuti441#

You may try it like this:

DECLARE @i int = 0
WHILE @i < 300 
BEGIN
    SET @i = @i + 1
    /* your code*/
END
5f0d552i

5f0d552i2#

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END
brjng4g3

brjng4g33#

I would prevent loops in general if i can, set approaches are much more efficient:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

Generate a set or sequence without loops

33qvvth1

33qvvth14#

In ssms we can use GO to execute same statement

Edit This mean if you put

some query

 GO n

Some query will be executed n times

ovfsdjhp

ovfsdjhp5#

Found some different answers that I combined to solve similar problem:

CREATE TABLE nummer (ID INTEGER PRIMARY KEY, num, text, text2);
WITH RECURSIVE
  for(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM for WHERE i < 1000000)
INSERT INTO nummer SELECT i, i+1, "text" || i, "otherText" || i FROM for;

Adds 1 million rows with

  • id increased by one every iteration
  • num one greater then id
  • text concatenated with id-number like: text1, text2 ... text1000000
  • text2 concatenated with id-number like: otherText1, otherText2 ... otherText1000000

相关问题