not exists with multiple primary keys

Posted on 2007-11-29
Last Modified: 2010-04-21
  I want to write a store procedure to delete the records in Table A not in Table B. Table A and Table B have the same primary keys. Since both of them use multiple primary keys, the following code doesn't work correctly.

delete from A
      where not exists
       from B
       inner join A
            A.k1= B.k1 and A.k2= B.k2 and
            A.k3= B.k3 and A.k4= B.k4 and A.k5= B.k5 and A.k6 = B.k6

Many thanks,
Question by:Jinghui Li
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 69

Expert Comment

by:Scott Pletcher
ID: 20374463
LEFT OUTER JOIN B ON A.k1= B.k1 and A.k2= B.k2 and
            A.k3= B.k3 and A.k4= B.k4 and A.k5= B.k5 and A.k6 = B.k6
LVL 22

Accepted Solution

dportas earned 500 total points
ID: 20374558
You were very close I think, but the extra reference to A was the problem (your subquery wasn't correlated because of it).

Untested. Make sure you test this out and have a backup and before you try it for real!

delete from A
      where not exists
       from B
            A.k1= B.k1 and A.k2= B.k2 and
            A.k3= B.k3 and A.k4= B.k4 and A.k5= B.k5 and A.k6 = B.k6

Author Closing Comment

by:Jinghui Li
ID: 31411684
I tried it. It works fine.
Thank you very much,

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question