Delete with EXCEPT and EXISTS Syntax


Delete rows from table2 (t2) that are not presented in Table1 (t1).

create table Table1 (C1 int,C2 char(1),C3 char(1))
INSERT INTO Table1 values (1,’A’,’X’), (1,’B’,’Y’),(2,’C’,’Z’),(1,’A’,’Z’)

create table Table2 (C1 char(1),C2 char(1),C3 char(1))
INSERT INTO Table2 values (1,’A’,’X’), (1,’B’,’Y’),(2,’C’,’Z’),(1,’A’,’Z’),(1,’B’,’X’)

DELETE t2
FROM Table2 AS t2
WHERE EXISTS
(
SELECT t2.*
EXCEPT
SELECT * FROM Table1
)

select * from Table2

drop table Table1
drop table Table2
Reference:
http://explainextended.com/2010/02/10/sql-server-except-all/

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s