T-SQL: Comparing Two Tables - Records that don't exist in second table

前端 未结 7 1355
小鲜肉
小鲜肉 2021-01-02 05:05

If UNION ALL is an addition in T-SQL. What is the equivalent of subtraction?

For example, if I have a table PEOPLE and a table

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 06:01

    You can use the EXCEPT operator to subtract one set from another. Here's a sample of code using EMPLOYEES and PEOPLE temporary tables. You'll need to use the field names with the EXCEPT operator as far as I know.

    CREATE TABLE #PEOPLE
    (ID INTEGER,
     Name NVARCHAR(50))
    
    CREATE TABLE #EMPLOYEE
    (ID INTEGER,
     Name NVARCHAR(50))
    GO
    
    INSERT #PEOPLE VALUES (1, 'Bob')
    INSERT #PEOPLE VALUES (2, 'Steve')
    INSERT #PEOPLE VALUES (3, 'Jim')
    INSERT #EMPLOYEE VALUES (1, 'Bob')
    GO
    
    SELECT ID, Name
    FROM #PEOPLE
    EXCEPT 
    SELECT ID, Name
    FROM #EMPLOYEE
    GO
    

    The final query will return the two rows in the PEOPLE table which do not exist in the EMPLOYEE table.

提交回复
热议问题