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