简体   繁体   中英

UPDATE performance for empty join

I have this bit of sql

DECLARE @tmpTable TABLE(idTransaction int PRIMARY KEY, Value money)
DECLARE @idStatement int = 0

UPDATE T 
       SET idStatement = @idStatement
FROM tbl_Transaction T
INNER JOIN @tmpTable ST on T.id = ST.idTransaction 

The table tbl_Transaction has about 250,000 rows in it (which i think is gunna be the cause of this), but when I run the query as it is it takes about 650ms to execute, even though the tmpTable is completely empty and the join will update no rows.

I am assuming this is something to do with how UPDATE works but can anyone shed any light on why? I know for an empty table I can check the row count but I am wanting to find out if this will affect the performance of my query when the tmpTable has rows in?

Any advice is greatly appreciated.

This is because it won't match indexes on the table variable the same way it will with a temp table. YOu could convert it to a temp table and that will most likely solve the problem. Alternatively, you could try this:

UPDATE T 
       SET idStatement = @idStatement
FROM tbl_Transaction T
WHERE T.id n IN (SELECT ST.idTransaction from @tmptable)

This will probably be slower than a temp table but faster than a join with a table variable

A trigger will fire even if you update to the same value

UPDATE T 
       SET idStatement = @idStatement
 FROM tbl_Transaction T
INNER JOIN @tmpTable ST 
   on T.id = ST.idTransaction 
  and idStatement <> @idStatement

if you need to also update to null

or (@idStatement == null and idStatement is not null)

And as stated in a comment try a #temp
Query optimization on Table is limited

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM