How do you write a sql statement for a "where in" clause regarding a compound key?

Using MSSQL 2005, I'm used to writing instructions like this:

delete
from myTable
where ID in (select ID from otherTable where deleted = 1)

How to do this if it otherTablehas a composite primary key?

The aggregate key has two columns:

docnum float
version int

(My google-fu suggests using CTE for this, but I have no experience with them.)

+3
source share
2 answers

In MS SQL you can do this:

DELETE T
FROM myTable T
INNER JOIN otherTable OT
  ON T.docnum = OT.docnum
  And T.version = OT.version

Similar syntax for updates too.

+2
source

You can also use the keyword exists :

delete t1
from myTable t1
where exists (
    select * from otherTable where docnum = t1.docnum and version = t1.version
)
+1
source

Source: https://habr.com/ru/post/1788345/


All Articles