title: SQL delete records only which are not in conflict with Foreign Constraint
body: <p>How can I delete the records from a table that are not referenced by any record in other tables via FK?</p>
  <p>I'm using SQL Server 2014. Example:</p>
  <pre><code>CREATE TABLE Persons (
      PersonID int NOT NULL PRIMARY KEY,
      PersonName varchar(20) NOT NULL);
  INSERT INTO Persons VALUES (1, 'Alistair'), (2, 'Bob'), (3, 'Cecile')
  
  CREATE TABLE Orders (
      OrderID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
      PersonID int FOREIGN KEY REFERENCES Persons(PersonID));
  INSERT INTO Orders values (1), (1), (3)
  
  DELETE FROM Persons //--&gt;The DELETE statement conflicted with the REFERENCE constraint FK__Orders__PersonID...
  </code></pre>
  <p>I only want to delete <em>Bob</em> from Persons (as there's no order belongs to him) and keep <em>Alistair</em> and <em>Cecile</em> (and no error message of course).</p>
  <p>Motivation: I need this for a maintenance job which removes obsolete or unneeded records. The solution I can think of <code>DELETE FROM Persons WHERE NOT EXISTS(SELECT 1 FROM Orders WHERE Orders.PersonID = Persons.PersonID)</code>
  is not really good, as in my real database there are many tables and FKs and also if someone introduces another FK, my code breaks. So looking for a more generic solution.</p>
  <p>UPDATE: just to expand why I'm looking for another solution than <code>DELETE ... WHERE NOT EXISTS</code> is that there are multiple tables in my database and I would need to list manually all of them in WHERE clause like <code>DELETE ... WHERE NOT EXISTS(...Table1...) AND NOT EXISTS(...Table2...) ... AND NOT EXISTS(...TableN...)</code> and if a developer adds <code>TableN+1</code>, my code also needs changing.
  So I'm hoping to have some SQL command / option that does what I want: only delete the non-conflicting records without the need of listing all constraints manually that the SQL engine is already aware of anyway.</p>