How to Insert N Numbers into a SQL Server Table using WHILE Loop

To insert numbers between 1 and 1000 into a table using WHILE Loop in a single transaction use the following code:

DECLARE @first AS INT
SET @first = 1
DECLARE @step AS INT
SET @step = 1
DECLARE @last AS INT
SET @last = 1000

BEGIN TRANSACTION
WHILE(@first <= @last) BEGIN INSERT INTO Table_Name VALUES(@first) SET @first += @step END COMMIT TRANSACTION

To insert all even numbers between 100 and 300 into a table using WHILE Loop in a single transaction use the following code:

DECLARE @first AS INT
SET @first = 100
DECLARE @step AS INT
SET @step = 2
DECLARE @last AS INT
SET @last = 300

BEGIN TRANSACTION
WHILE(@first <= @last) BEGIN INSERT INTO Table_Name VALUES(@first) SET @first += @step END COMMIT TRANSACTION

To insert all odd numbers between 99 and 199 into a table using WHILE Loop in a single transaction use the following code:

DECLARE @first AS INT
SET @first = 99
DECLARE @step AS INT
SET @step = 2
DECLARE @last AS INT
SET @last = 199

BEGIN TRANSACTION
WHILE(@first <= @last) BEGIN INSERT INTO Table_Name VALUES(@first) SET @first += @step END COMMIT TRANSACTION

If the post helped you, please share it:
Pin It

2 comments to How to Insert N Numbers into a SQL Server Table using WHILE Loop

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">