简体   繁体   中英

T-SQL - stored procedure - “IF EXISTS” vs. “WHERE EXISTS”

Is it better to write:

IF EXISTS (SELECT ...) OR EXISTS (SELECT ...)
  BEGIN
    INSERT INTO myTable
    VALUES ('myValue1', 'myValue1')
  END

Or to write:

INSERT INTO myTable
SELECT 'myValue1', 'myValue1'
WHERE EXISTS (SELECT ...) OR EXISTS (SELECT ...)

?

I mean better in terms of performance and readability.

Pileggi

You should use the latter, not really a question of efficiency (I suspect there is no significant difference between the two), but the least likely to meet a race condition . If two inserts run concurrently, there is a small chance that when using the first method the same record is inserted by another thread in between checking if the value exists and actually doing the insert. Since both the check and the insert are done using the same lock in the latter this is less likely to occur.

So in my opinion, both readability and performance come a very distant second in terms of importance to accuracy and thread safety.

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