Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hello friends...

I have following query.
SQL
declare @query varchar(500)
set @query='select * from openquery(abc,''select Avg(value) from ihrawdata'')'

declare @result varchar(20)
exec (@query)

this code is working perfectly. but when i tried following
SQL
set @result=exec(@query)

it issued an error as follows
invalid syntax near exec.
plz help
Posted
Updated 3-Sep-14 0:23am
v3
Comments
Kornfeld Eliyahu Peter 3-Sep-14 6:27am    
You should use sp_executesql - http://msdn.microsoft.com/en-us/library/ms188001.aspx
TAUSEEF KALDANE 3-Sep-14 6:29am    
i had used sp_executesql but it didn't work.
Rich.Edwards 3-Sep-14 6:29am    
You can't stored the results returned from the query in a varchar(20)

What were you planning on using @result for?
TAUSEEF KALDANE 3-Sep-14 6:38am    
i want the value for further calculations.

EXEC does not return a value: so you cannot use it to "fetch" a value and store it for later.
You would need to use sp_executesql instead: http://stackoverflow.com/questions/5439005/set-var-exec-storedprocedure[^]
 
Share this answer
 
Comments
TAUSEEF KALDANE 3-Sep-14 6:44am    
sir,
i can't use sp_executesql due to open query. it started throwing errors
See if you want to set the exec value to your declare variable then you have to use sp_executesql on the following way
declare @query nvarchar(500)
declare @result  varchar(20) 
set @query=' select  @cnt=Avg(value) from ihrawdata' 
--Set the exec value to your declare variable
EXECUTE sp_executesql @query, N'@avg varchar(20) OUTPUT', @avg=@result OUTPUT
Select @result
 
Share this answer
 
exec does not return a single value , it returns a tabular format data , so you can not store it into the varchar type variable
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900