这是@Aleksandr Fedorenko的答案的修改版本,其中添加了WHERE子句:
UPDATE x
SET x.CODE_DEST = x.New_CODE_DEST
FROM (
SELECT CODE_DEST, ROW_NUMBER() OVER (ORDER BY [RS_NOM]) AS New_CODE_DEST
FROM DESTINATAIRE_TEMP
) x
WHERE x.CODE_DEST <> x.New_CODE_DEST AND x.CODE_DEST IS NOT NULL
通过添加WHERE子句,我发现以后的更新性能得到了极大的提高。即使该值已经存在,SQL Server似乎也会更新该行,并且这样做需要花费时间,因此添加where子句可使它仅跳过该值未更改的行。我不得不说我对它运行查询的速度感到惊讶。
免责声明:我不是DB专家,并且我为我的子句使用PARTITION BY,因此此查询的结果可能不完全相同。对我而言,该列是客户的已付款订单,因此设置后该值通常不会更改。
还要确保您具有索引,尤其是在SELECT语句上具有WHERE子句的情况下。过滤索引对我非常有用,因为我正在根据付款状态进行过滤。
我的查询使用PARTITION
UPDATE UpdateTarget
SET PaidOrderIndex = New_PaidOrderIndex
FROM
(
SELECT PaidOrderIndex, SimpleMembershipUserName, ROW_NUMBER() OVER(PARTITION BY SimpleMembershipUserName ORDER BY OrderId) AS New_PaidOrderIndex
FROM [Order]
WHERE PaymentStatusTypeId in (2,3,6) and SimpleMembershipUserName is not null
) AS UpdateTarget
WHERE UpdateTarget.PaidOrderIndex <> UpdateTarget.New_PaidOrderIndex AND UpdateTarget.PaidOrderIndex IS NOT NULL
-- test to 'break' some of the rows, and then run the UPDATE again
update [order] set PaidOrderIndex = 2 where PaidOrderIndex=3
如果列不可为空,则不需要“ IS NOT NULL”部分。
当我说性能提升很大时,我的意思是更新少量行时基本上是瞬时的。使用正确的索引,我能够获得与“内部”查询本身花费的时间相同的更新:
SELECT PaidOrderIndex, SimpleMembershipUserName, ROW_NUMBER() OVER(PARTITION BY SimpleMembershipUserName ORDER BY OrderId) AS New_PaidOrderIndex
FROM [Order]
WHERE PaymentStatusTypeId in (2,3,6) and SimpleMembershipUserName is not null
UPDATE myCol = myCol+1 FROM MyTable WHERE ID=@MyID