Trying to delete when not exists is not working. M

2019-06-21 19:32发布

问题:

I am currently trying to delete from Table A where a corresponding record is not being used in Table B. Table A has Section, SubSection, Code, Text as fields, where the first three are the Primary Key. Table B has ID, Section, SubSection, Code as fields, where all four are the Primary Key. There are more columns, but they are irrelevant to this question...just wanted to point that out before I get questioned on why all columns are part of the Primary Key for Table B. Pretty much Table A is a repository of all possible data that can be assigned to a entity, Table B is where they are assigned. I want to delete all records from table A that are not in use in Table B. I have tried the following with no success:

DELETE FROM Table A 
WHERE NOT EXISTS (SELECT * from Table B 
WHERE A.section = B.section
AND A.subsection = B.subsection
AND A.code = b.code)

If I do a Select instead of a delete, I get the subset I am looking for, but when I do a delete, I get an error saying that there is a syntax error at Table A. I would use a NOT IN statement, but with multiple columns being part of the Primary Key, I just don't see how that would work. Any help would be greatly appreciated.

回答1:

In sql server,when using not exists, you need to set an alias for the table to be connected, and in the delete statement, to specify the table to delete rows from.

DELETE a FROM Table_A a 
WHERE NOT EXISTS (SELECT * from Table_B b 
WHERE a.section = b.section
AND a.subsection = b.subsection
AND a.code = b.code)


回答2:

Please try :

DELETE FROM Table A 
WHERE NOT EXISTS (SELECT 1 from Table B 
WHERE A.section = B.section
AND A.subsection = B.subsection
AND A.code = b.code)

1 is just a placeholder, any constant/single non-null column will work.



回答3:

Try something like this:

delete from Table_A
    where (section, subsection, code) not in (select section, 
                                                     subsection, 
                                                     code 
                                                from Table_B)