更新/设置订购?

时间:2015-06-02 22:13:34

标签: sql-server

我很好奇以下update声明未按预期设置的原因:

DECLARE @int INT
SET @int = 0;

UPDATE #jc_TEMP
SET Num =  @int, @int = @int + 1

我希望这会将第一行设置为0然后更新。首先在字段之前设置局部变量吗?

1 个答案:

答案 0 :(得分:1)

The process of doing an update on a table with a variable that then gets assigned repeatedly in the same statement is sometimes referred to as a "quirky update". It's an undocumented feature of SQL Server which, if controlled correctly will quickly update rows in the order of the primary key. I've used it on a few occasions for things like running totals in pre-2012. There are quite a few gotchas, as with any undocumented procedure, but a good intro is this article from SSC

http://www.sqlservercentral.com/articles/T-SQL/68467/

To answer the first question, yes. variables get evaluated first. I just know this from trial and error, so I can't point you to a specific article documenting that behavior.

Be warned as I mentioned above that unless you do this right, you can't be guaranteed of the order in which the updates will occur. If you're doing this in a production system, I'd recommend joining the table to itself and using the row_number() window function instead. Something like:

update a
set num = x.num
from #jc_temp a
inner join (select num = row_number() over (order by num)
            from #jc_temp) x
    on a.num = x.num