Search code examples
t-sqlssms-2014

Is there a shortcut to deleting all in one table not in another?


Are there any shortcuts for deleting everything in one table that does not exist in the second?

I know I can do this:

    DECLARE @Table1 TABLE (ID INT)
    DECLARE @Table2 TABLE (ID INT)

    INSERT INTO @Table1 VALUES (1),(2),(3),(4)
    INSERT INTO @Table2 VALUES (3),(4)

    DELETE t1
        FROM @Table1 t1
            WHERE NOT EXISTS (SELECT 1 FROM @Table2 t2 WHERE t2.ID = t1.ID)

    SELECT * FROM @Table1

However, I have over 600 columns, so you can see why I might be reluctant to go that route if there's another way. What I WANT to do would look like this:

    DECLARE @Table1 TABLE (ID INT)
    DECLARE @Table2 TABLE (ID INT)

    INSERT INTO @Table1 VALUES (1),(2),(3),(4)
    INSERT INTO @Table2 VALUES (3),(4)

    DELETE @Table1
        EXCEPT SELECT * FROM @Table2

That EXCEPT has been very handy in dealing with this project I'm working on, but I guess it's limited.


Solution

  • Please use this:

    DELETE FROM @Table1 WHERE  BINARY_CHECKSUM(*) NOT IN(SELECT BINARY_CHECKSUM(*) FROM @Table2);
    

    But be carefull, if your table contains float data types. In very rare cases wrong checksum may be calculated. But, these cases are rare and random, no problems will remain after second delete iteration.