Link to home
Start Free TrialLog in
Avatar of DecaysChampion
DecaysChampion

asked on

Variable declaration in EXEC

Hi,

    I'm having a strange problem with a query that I hope someone may have seen before.  I've declared a variable @statvar as type int and @cmd1 as a varchar (255).

The statement where I'm having the problem is as follows:

set @cmd1='select @statvar=count(*) from '+@dbname+'..sysfiles'

exec(@cmd1)

I keep getting the error "Must declare the variable @statvar"

I've worked around the problem by eliminating the '@statvar= ' and sending the results to a temp table instead, but I'm curious as to why the original query doesn't work.  I don't have any 'go' statements prior to it.

Thanks in advance!
ASKER CERTIFIED SOLUTION
Avatar of SteveGTR
SteveGTR
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mathavra
mathavra

Try "select" instead of "set" as below:

select @cmd1='select @statvar=count(*)from '+@dbname+'..sysfiles'

Or

Is it OK for you move the declare statments just before the SQL statment as below:

declare @statvar int
select @cmd1='select @statvar=count(*)from '+@dbname+'..sysfiles'
Avatar of DecaysChampion

ASKER

Mathavra,

The problem occurs regardless of where the DECLARE statement is and I've verified that the actual command is being correctly stored in @cmd1 using SET (It occurs during the exec statement).
When you assign value to a variable inside the dynamic sql that variable is treated as local variable to that sql statement. When you execute a dynamic sql it treats that sql statement as new bunch of statement (what i understood might be it must be executing with new connection)
mq is correct, it's seen as a local variable, ergo, this will work fine as @statvar is declared within the string:

set @cmd1='declare @statvar int; select @statvar=count(*)from '+@dbname+'..sysfiles; select @statvar;'
exec(@cmd1)
You are correct Charles, but after the exec returns the @statvar will be unaccessible (out of scope).

My cursor example get's around this as does DecaysChampion's temp table solution.
Proof of theory ;o)
Whatever I proposed did not work for me also. I just tried. Sorry for the incorrect answer.

I think, each EXEC statement is executed as a (separate) batch and that is reason why it is not recognizing the variable declaration. Also, it cannot return any variable since it is out of scope as mqmanoj.

May be you want to use stored procedure and return the appropriate value from the stored procedure.
Thank you all for your comments!
Sorry to be late but you can set return parameters from dynamic sql and dynamic sql SP calls if you use sp_executesql instead of exec.

You cannot set parameters from an exec but you can from sp_executesql.