Connecting Tech Pros Worldwide Forums | Help | Site Map

Set a variable to result of executed dynamic query

Newbie
 
Join Date: Oct 2007
Posts: 1
#1: Oct 18 '07
Is it possible or not:
declare @query varchar(500)
declare @var varchar(50)
@query='select U_Id from tblUser where U_Id='+100
@var = exec(@query)


plz help me..............

Jim Doherty's Avatar
Moderator
 
Join Date: Aug 2007
Location: Derbyshire,England
Posts: 639
#2: Oct 18 '07

re: Set a variable to result of executed dynamic query


Quote:

Originally Posted by rupeshjain

Is it possible or not:
declare @query varchar(500)
declare @var varchar(50)
@query='select U_Id from tblUser where U_Id='+100
@var = exec(@query)


plz help me..............


Your variable is assigned at the point when you return the value of your presumably 'single' value sql execution return value into the variable @query. Compare my layout to yours

Expand|Select|Wrap|Line Numbers
  1.  
  2. declare @query varchar(500)
  3. declare @var varchar(50)
  4.  
  5. SELECT @query = U_Id from tblUser where U_Id=100
  6.  
  7.  
If you then need to pass the value from @query to @var
then thats a matter for you
ie
Expand|Select|Wrap|Line Numbers
  1.  SELECT @var=@query
Regards

Jim :)
Newbie
 
Join Date: Oct 2008
Posts: 1
#3: Oct 24 '08

re: Set a variable to result of executed dynamic query


Quote:

Originally Posted by rupeshjain

Is it possible or not:
declare @query varchar(500)
declare @var varchar(50)
@query='select U_Id from tblUser where U_Id='+100
@var = exec(@query)


plz help me..............

try to use EXECUTE sp_executesql
ck9663's Avatar
Expert
 
Join Date: Jun 2007
Posts: 1,925
#4: Oct 24 '08

re: Set a variable to result of executed dynamic query


Looks like you're trying to store the value of u_id to a variable. Be careful with SELECT, it could lead to undetected logical error, not syntax errors.

Depending on your requirement, a SET command might also be considered.

Read my blog about the difference between SET and SELECT

Good luck.

-- CK
Reply