Question

Question 1: with in store procedure,can we declare variable dynamically like below:

declare @i int =1;
declare @s nvarchar(max) ='';
while(@i<5)  
begin 
set @s = concat('declare @temp',@i,' nvarchar(max);');
exec (@s);
set @i=@i + 1;
end

if we can declare the variable dynamically like above then what will be the scope of this kind of variable? with in that store procedure?

Question 2: we do not need to declare session variable in mysql so can we have same kind of session variable in sql server.

Actually I am converting mysql script to sql server script and I am finding difficulties with variable declaration because in mysql I have used session variables.

Thanks in advance..

Was it helpful?

Solution

Yes, and no

You can declare the variable dynamically, and exec the command, but its scope will be within that exec statement, so it will vanish afterwards.

You can do

declare @t nvarchar(100) = 'declare @v int; select @v = 1; select @v+1'
exec (@t)

Or you can pass variables to commands with sp_executesql.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top