retrieving values from one select statement

  • ok, this is probably the most stupid t-sql question you ever heard... but hey, we all started somewhere

    i've be trying to tell my sweet procedure that i want to retrieve the fields from my select and assign them to variables, knowing that my select will return only one record....smthg like:

    select * from mytable where mytable.id = 1

    set @var1 = mytable.field1

    set @var1 = mytable.field2 ....

    but of course it won't work, which makes me write as many selects as the fields i have, and i really don't want to do that:

    set @var1 = (select mytable.field1 from mytable where mytable.id = 1)

    set @var2 = (select mytable.field2 from mytable where mytable.id = 1) etc...

    mmmm .... any hint for the newbie?

  • Yes rethink this.  What are you trying to do in that module?

  • In addition to re-thinking, it can't hurt to learn the correct syntax for assigning multiple variables at once, using SELECT and not SET:

    Instead of:

    set @var1 = (select mytable.field1 from mytable where mytable.id = 1)

    set @var2 = (select mytable.field2 from mytable where mytable.id = 1) etc...

    Use:

    Select

      @var1 = column1,

      @var2 = column2,

      ...

      @varN = columnN

    From mytable

    Where id = 1

     

  • oooops ok

    tx!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply