Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 672
pencilCake Avatar asked Feb 21 '14 08:02

pencilCake


People also ask

How do you use multiple WHILE loops in SQL?

Nested SQL While Loop SyntaxStep 1: First, it checks for the condition inside the first While loop. Step 2: It will verify the condition in the Nested SQL While Loop (second While loop). If the result is True, the code inside the second While loop begin… end will execute.

How can we insert multiple rows at a time into the table?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

How do you create a loop table in SQL?

First, create two table variables - and store in them 1-5, and 1-53 (for days and weeks). Then cartesian join the two and you're done! Change the last SELECT statement into an insert into your destination table and you're done.


2 Answers

You may try it like this:

DECLARE @i int = 0 WHILE @i < 300  BEGIN     SET @i = @i + 1     /* your code*/ END 
like image 92
Rahul Tripathi Avatar answered Sep 22 '22 20:09

Rahul Tripathi


DECLARE @first AS INT = 1 DECLARE @last AS INT = 300  WHILE(@first <= @last) BEGIN     INSERT INTO tblFoo VALUES(@first)     SET @first += 1 END 
like image 33
124 Avatar answered Sep 21 '22 20:09

124