sql server - Update/Set ordering? -


i'm curious why following update statement not setting expected:

declare @int int set @int = 0;  update #jc_temp set num =  @int, @int = @int + 1 

i expect set first row 0 , update. local variables set first, before fields?

the process of doing update on table variable gets assigned repeatedly in same statement referred "quirky update". it's undocumented feature of sql server which, if controlled correctly update rows in order of primary key. i've used on few occasions things running totals in pre-2012. there quite few gotchas, undocumented procedure, intro article ssc

http://www.sqlservercentral.com/articles/t-sql/68467/

to answer first question, yes. variables evaluated first. know trial , error, can't point specific article documenting behavior.

be warned mentioned above unless right, can't guaranteed of order in updates occur. if you're doing in production system, i'd recommend joining table , using row_number() window function instead. like:

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

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -