Running a 'For' Loop in MS SQL

There really isn't a 'for' loop in MS SQL, but you can do basically the same thing

First of all, I am far from a SQL master; I would even go as far to say I would be lucky to be an amatuer at best.  But I did stumble upon a convenient way for populating a lot of new rows using a simple technique that is not using a bulk insert.  It is actually pretty basic stuff, but nice to know if you were Googling for it like I was.

 

DECLARE @count INT

SET @count = 0

WHILE (@count < 40)

BEGIN

   INSERT INTO some_table ([columnA], [columnB]) VALUES ('val1', 'val2')

   SET @count = (@count + 1)

END

 

All that was really done is a manual 'For' loop using the SQL WHILE loop.  Just set the number in WHILE (@count < 40) to however many times you want the loop to run.

Pingbacks and trackbacks (2)+

Comments are closed