SQL: How to properly check if a record exists

前端 未结 9 1342
粉色の甜心
粉色の甜心 2020-11-28 01:23

While reading some SQL Tuning-related documentation, I found this:

SELECT COUNT(*) :

  • Counts the number of rows.
  • Often is improper
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 02:18

    I would prefer not use Count function at all:

    IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
         
    

    For example if you want to check if user exists before inserting it into the database the query can look like this:

    IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
    BEGIN
        INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
    END
    

提交回复
热议问题