Assigning values in Variables in a single Select

  • I am sure this could be one of those questions you get in "how expert you are in sql" quizzes, but here goes...

    declare @a int, @b-2 int, @C int, @d int

    select @a = 1

    , @b-2 = 2

    , @C = @a + @b-2

    , @d = @C * 2

    select @a

    , @b-2

    , @C

    , @d

    That works like a treat returning the values:

    1, 2, 3, 6

    So, is it a t-sql or a microsoft sql feature?

    Does it strike odd to you that it does each in the sequence of being typed? I assumed a SELECT is a Batch that is evaluated as a whole not in steps... So I wouldn't be surprised if the results were:

    1, 2, null, null

    I have to admit, I like this "shorthand" but I would be careful using it because you write some code and some other dude starts copy pasting these columns in the wrong order, you get a fist full of "null" values!

  • Leon Venediktou (3/10/2010)


    I am sure this could be one of those questions you get in "how expert you are in sql" quizzes, but here goes...

    declare @a int, @b-2 int, @C int, @d int

    select @a = 1

    , @b-2 = 2

    , @C = @a + @b-2

    , @d = @C * 2

    select @a

    , @b-2

    , @C

    , @d

    That works like a treat returning the values:

    1, 2, 3, 6

    So, is it a t-sql or a microsoft sql feature?

    Does it strike odd to you that it does each in the sequence of being typed? I assumed a SELECT is a Batch that is evaluated as a whole not in steps... So I wouldn't be surprised if the results were:

    1, 2, null, null

    I have to admit, I like this "shorthand" but I would be careful using it because you write some code and some other dude starts copy pasting these columns in the wrong order, you get a fist full of "null" values!

    You need to be careful using this. BOL says this about multiple assignment using SELECT (in this article):

    Caution:

    If there are multiple assignment clauses in a single SELECT statement, SQL Server does not guarantee the order of evaluation of the expressions. Note that effects are only visible if there are references among the assignments.

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

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