How can INSERT INTO a table 300 times within a loop in SQL? How can INSERT INTO a table 300 times within a loop in SQL? sql-server sql-server

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


You may try it like this:

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


DECLARE @first AS INT = 1DECLARE @last AS INT = 300WHILE(@first <= @last)BEGIN    INSERT INTO tblFoo VALUES(@first)    SET @first += 1END


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