How to write SQL statement with dynamic where clause?

How do you write a sql statement for a 'where in' clause against a composite key?

  • Using MSSQL 2005 I am used to writing a statement like this: delete from myTable where ID in (select ID from otherTable where deleted = 1) How can I do this when otherTable has a composite primary key? The composite key has two columns: docnum float version int (My google-fu suggests using CTEs to do this however I have no experience with them.)

  • Answer:

    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 There's a similar syntax for updates too.

Antony at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

You can also use the exists keyword: delete t1 from myTable t1 where exists ( select * from otherTable where docnum = t1.docnum and version = t1.version )

pjotr

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.