简体   繁体   中英

How to delete rows in tableA which are found in tableB based on two specific columns

If i have tableA and tableB with three columns:

colA | colB | colC

And i need to look at only colA and colB

I have this so far, but it keeps deleting every row in my tableA:

DELETE

FROM
        dbA.dbo.tableA
WHERE 
        EXISTS(
                SELECT DISTINCT
                       a.colA
                       ,a.colB
                FROM
                        dbB.dbo.tableB b WITH(NOLOCK)
                            INNER JOIN dbA.dbo.tableA a WITH(NOLOCK) ON
                                b.colA = a.colA
                        AND
                                b.colB = b.colB
              )

Obviously i am doing something wrong but i have hit a wall and can't seem to figure out why it is still deleting all rows in tableA

Thank you.

DELETE FROM dbA.dbo.tableA 
WHERE EXISTS
(
  SELECT *
  FROM dbB.dbo.tableB b WITH(NOLOCK) 
  where
      b.colA = dbA.dbo.tableA .colA 
  AND b.colB = dbA.dbo.tableA .colB 
) 

Try the simplified form:

DELETE dbA.dbo.tableA
FROM dbA.dbo.tableA a WITH(NOLOCK)
JOIN dbB.dbo.tableB b WITH(NOLOCK)
  ON 
      b.colA = a.colA
  AND b.colB = a.colB

AND

actually there is an error in your query near the line

                            b.colB = b.colB

which forces extra deletions from table a

AND

You can use EXISTS instead of JOIN - as mentioned in @Stefan's answer, result will be just the same but the query will be more readable

Can you possibly make it a simpler statement?

DELETE
FROM dbA.dbo.TableA a
JOIN dbA.dbo.TableB b ON b.colA = a.colA

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