Link to home
Start Free TrialLog in
Avatar of LeTay
LeTay

asked on

Result of a dynamic select into a variable in SQL Server 2005

I need to build a select (all that in a stored procedure) based on several conditions passed to the procedure
The select should return the result in a local variable
Something like this

declare @Q varchar(1000)
declare @R integer
select @Q = 'select @R = count(*) from Lots' -- @R is an output argument
exec (@Q)


This fails (@R must be declared) on the exec
Is there another way not being simply this : select @R = count(*) from Lots'

(I need this @Q because it is being build at several places
Avatar of Steve Wales
Steve Wales
Flag of United States of America image

Found this:
stackoverflow.com/questions/14399020/storing-value-in-variable-using-dynamic-sql-in-sql-server

Tested it on my test server and it seems to work just fine.

Good luck, hope that's helpful.
ASKER CERTIFIED SOLUTION
Avatar of sachinpatil10d
sachinpatil10d
Flag of India 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
sjwales - Just so you know, EE is cracking down on what it refers to as 'blind links' essentially a link to a competing site with no context other than 'go here'.  To avoid any conflicts, please add a little color commentary when giving an 'go here' answer.  TIA.
jimhorn - thanks for the heads up.  Did a bit of a search in the Community Support area on this stance and have seen the why's and wherefore's behind the stance and it's understandable.

sachinpatil10d's answer does the same thing though, so the OP has his answer if mine gets deleted by admin.
Yep.  The 'add color to the link' is kind of the happy medium they came up with.   Also, this applies only to competitors sites which have a higher chance of going bad (or being a big pile of goo).  Manufacturers sites such as TechNet are considered okay.