Order of execution in SQL Server variable assignment using SELECT

时光毁灭记忆、已成空白 提交于 2019-11-30 13:43:54
Michael Fredrickson

For variable assignment, Martin Smith answers this question here referencing MSDN:

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.

But...

If we're dealing with tables, instead of with variables, it is a different story.

In this case, Sql Server uses an All-At-Once operation, as discussed by Itzik Ben-Gan in T-Sql Fundamentals.

This concept states that all expressions in the same logical phase are evaluated as if the same point in time... regardless of their left-to-right position.

So when dealing with the corresponding UPDATE statement:

DECLARE @Test TABLE (
    i INT,
    j INT
)

INSERT INTO @Test VALUES (0, 0)

UPDATE @Test
SET
    i = i + 10,
    j = i

SELECT 
    i, 
    j 
FROM 
    @Test

We get the following results:

i           j
----------- -----------
10          0   

And by using the All-At-Once evaluation... in Sql Server you can swap column values in a table without an intermediate variable / column.

Most RBDMSs behave this way as far as I know, but MySql is an exception.


EDIT:

Note that effects are only visible if there are references among the assignments.

I understand this to mean that if you have a SELECT statement such as the following:

SELECT
    @A = ColumnA,
    @B = ColumnB,
    @C = ColumnC
FROM MyTable

Then it doesn't matter what order the assignments are performed in... you'll get the same results no matter what. But if you have something like...

SELECT
    @A = ColumnA,
    @B = @A,
    @C = ColumnC
FROM MyTable

There is now a reference among the assignments (@B = @A), and the order that @A and @B are assigned now matters.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!