Assigning Multiple Variables with Values at the same time

  • Hello Everyone

    Is there a way to assign values to multiple variables with one query?

    for eaxmple, can this be accomplished :

    DECLARE @FirstName varchar(25)

    DECLARE @MiddleName varchar(25)

    DECLARE @LastName varchar(25)

    SET @FirstName, @MiddleName, @LastName =

    (

    SELECT

    FirstName, MiddleName, LastName

    FROM

    SomeTable

    WHERE SomeColumn = SomeValue

    )

    The only way that I know is one at a time. One query to one variable

    Thanks in advance

    Andrew SQLDBA

  • SELECT TOP 1

    @FirstName = FirstName,

    @MiddleName = MiddleName,

    @LastName = LastName

    FROM

    SomeTable

    WHERE SomeColumn = SomeValue

    ORDER BY SomeOtherColumn

    Please note that I added TOP 1 together with an ORDER BY to get a deterministic result. Otherwise you'd get the "last selected value", which is pretty much random.



    Lutz
    A pessimist is an optimist with experience.

    How to get fast answers to your question[/url]
    How to post performance related questions[/url]
    Links for Tally Table [/url] , Cross Tabs [/url] and Dynamic Cross Tabs [/url], Delimited Split Function[/url]

  • Thanks Lutz

    That works perfectly. I have always used SET, which will allow only one value, SELECT allows multiple values.

    Another fundamental difference between SET and SELECT is that, you can use SELECT to assign values to more than one variable at a time. SET allows you to assign data to only one variable at a time. Here's how:

    /* Declaring variables */

    DECLARE @Variable1 AS int, @Variable2 AS int

    /* Initializing two variables at once */

    SELECT @Variable1 = 1, @Variable2 = 2

    /* The same can be done using SET, but two SET statements are needed */

    SET @Variable1 = 1

    SET @Variable2 = 2

    Andrew SQLDBA

  • One thing you may not know is that you can reference variables assigned previously in the select statement:

    declare @MonthStart datetime, @MonthEnd datetime;

    select @MonthStart = dateadd(month, DateDiff(month, 0, GetDate()), 0),

    @MonthEnd = dateadd(ms, -3, dateadd(month, 1, @MonthStart));

    select @MonthStart, @MonthEnd;

    Wayne
    Microsoft Certified Master: SQL Server 2008
    Author - SQL Server T-SQL Recipes


    If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
    Links:
    For better assistance in answering your questions
    Performance Problems
    Common date/time routines
    Understanding and Using APPLY Part 1 & Part 2

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

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