Generate Variables Through T-SQL Is it possible to generate variables solely through code?  If you have a base variable name, and add an int to the end of the name, could you generate variables?  Something similar to the below?

In the end I would want this syntax to generate 4 variables


@newlygeneratedvariable1
@newlygeneratedvariable2
@newlygeneratedvariable3
@newlygeneratedvariable4



Declare @i int, @totalvariables int

Set @totalvariables = '4'

for @i &lt;= 4
Set @i = 1

    Declare @newlygeneratedvariable + @i 
    Print 

    @i = @i + 1

Next @i
You can do something like this:

DECLARE @i INT = 1
DECLARE @totalvars INT = 5
DECLARE @newvar VARCHAR(50) = ''

WHILE @i &lt; @totalvars

BEGIN

SET @newvar = 'DECLARE @newvar' + CONVERT(VARCHAR(50), @i) + ' = ?;'

SET @i += 1

RAISERROR (@newvar, 0, 1) WITH NOWAIT;

END


So we're all clear, this won't create variables for you unless it's part of a larger block of dynamic SQL. You're probably better off using a temp table. But on the off chance you're using more dynamic SQL, you could use a loop like this to append the variable declarations just fine.