Select into

  • I have a question regarding passing values into two variables.

    if have a table and I want to return a value into a variable how can I accomplish this without using a cursor. See Below for an example of what I am trying to do.

    lets say i have a table (table1) with two columns (col1, col2). I want to select a row and pass the 2 values into parameters

    (this is the example of the select returning 1 row)

    select col1, col2

    from table1

    where col1 = 1

    lets say the values received are 1,scott

    I want to declare variables and put the values into them, however the code below does not work:

    Declare @nValue1 int

    Declare @sValue2 varchar(25)

    Select col1, col2

    Into @nValue1, @sValue2

    From table1

    where col1 = 1

    If i run this i get an error. Can this be done another way without using a cursor. I can use a cursor, but for what I am looking to do I believe it would be much quicker if I could just accomplish this with a simple select.

    Any help would be great. Thx, Scott.

  • You're close if I understand what you're asking. Declare your variables as before, then do this:

    select @nvalue1=col1, @svalue2=col2

    from table1

    where col1 = 1

    Andy

    http://www.sqlservercentral.com/columnists/awarren/

  • You are the man. So simple and I was so close. I went bald pulling my hair out last night. 🙂 Thanks Andy. Scott.

    You're close if I understand what you're asking. Declare your variables as before, then do this:

    select @nvalue1=col1, @svalue2=col2

    from table1

    where col1 = 1

    Andy

    http://www.sqlservercentral.com/columnists/awarren/

    [/quote]

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

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