Set a variable to result of executed dynamic query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rupeshjain
    New Member
    • Oct 2007
    • 1

    Set a variable to result of executed dynamic query

    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
    Recognized Expert Contributor
    • Aug 2007
    • 897

    #2
    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

    Code:
     
    declare @query varchar(500)
    declare @var varchar(50)
     
    SELECT @query = U_Id from tblUser where U_Id=100
    If you then need to pass the value from @query to @var
    then thats a matter for you
    ie
    Code:
     SELECT @var=@query
    Regards

    Jim :)

    Comment

    • chupok
      New Member
      • Oct 2008
      • 1

      #3
      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

      Comment

      • ck9663
        Recognized Expert Specialist
        • Jun 2007
        • 2878

        #4
        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

        Comment

        Working...