I have two tables with the same number of columns with no primary keys (I know, this is not my fault). Now I need to delete all rows from table A that exists in table B (they are equal, each one with 30 columns).
The most immediate way I thought is to do a INNER JOIN
and solve my problem. But, write conditions for all columns (worrying about NULL
) is not elegant (maybe cause my tables are not elegant either).
I want to use INTERSECT
. I am not knowing how to do it? This is my first question:
I tried (SQL Fiddle):
declare @A table (value int, username varchar(20))
declare @B table (value int, username varchar(20))
insert into @A values (1, 'User 1'), (2, 'User 2'), (3, 'User 3'), (4, 'User 4')
insert into @B values (2, 'User 2'), (4, 'User 4'), (5, 'User 5')
DELETE @A
FROM (SELECT * FROM @A INTERSECT SELECT * from @B) A
But all rows were deleted from table @A
.
This drived me to second question: why the command DELETE @A FROM @B
deletes all rows from table @A
?
DELETE A
and that does not run. Right now you are deleting @A CROSS JOIN (something else). Which deletes everything if there is at least one row in something else. Look at the query plan to see this. – Agley