I am trying to populate a sql variable with a value. It works when the code is like this:
declare @num_records int
set @num_records = ( select distinct count(*) as num_recs
from dbo.tbllookup )
print @num_records
For example purpose I have made my query simpler but its a complex query and I want to put it in variable as I have to reuse the part of the query somewhere else. So I tried this but it does not work. The error says “Incorrect syntax near the keyword ‘exec’.”
declare @num_records int
declare @sqlstr varchar(200)
set @sqlstr = '( select distinct count(*) as num_recs
from dbo.tbllookup )'
set @num_records = exec(@sqlstr)
print @num_records
I am a sql query newbie. So just want to understand the concept and want to know what I am doing wrong here.
Thanks.
you need to use sp_executeSQL with an output parameter
See example here at the bottom Changing exec to sp_executesql doesn’t provide any benefit if you are not using parameters correctly