How to Delete Rows using Inner Join In MS SQL Server Examples

I want to delete using INNER JOIN in SQL Server 2014. But I get error,

DELETE FROM WorkRecord2
INNER JOIN Employee ON EmployeeRun=EmployeeNo
WHERE Company = '5' AND Date = '2017-07-16'.

Answers:

You need to specify what table you are deleting from, here is a version with an alias:

DELETE w
FROM WorkRecord2 w
INNER JOIN Employee e
  ON EmployeeRun=EmployeeNo
WHERE Company = '5' AND Date = '2017-07-16'.

Or

Just add the name of the table between DELETE and FROM from where you want to delete records because we have to specify the table to delete. Also remove ORDER BY clause because there is nothing to order while deleting records.

So your final query should be like this:

  DELETE WorkRecord2
      FROM WorkRecord2
INNER JOIN Employee
        ON EmployeeRun=EmployeeNo
     WHERE Company = '5'
       AND Date = '2017-07-16';

Or

In SQL Server Management Studio I can easily create a SELECT query.

SELECT Contact.Naam_Contactpersoon, Bedrijf.BedrijfsNaam, Bedrijf.Adres, Bedrijf.Postcode
FROM Contact
INNER JOIN Bedrijf ON Bedrijf.IDBedrijf = Contact.IDbedrijf
I can execute it, and all my contacts are shown.

Now change the SELECT to a DELETE:

DELETE Contact
FROM Contact
INNER JOIN Bedrijf ON Bedrijf.IDBedrijf = Contact.IDbedrijf
All the records you saw in the SELECT statement will be removed.

You may even create a more difficult inner join with he same procedure, for example:

DELETE FROM Contact
INNER JOIN Bedrijf ON Bedrijf.IDBedrijf = Contact.IDbedrijf
INNER JOIN LoginBedrijf ON Bedrijf.IDLoginBedrijf = LoginBedrijf.IDLoginBedrijf.


Post a Comment

Previous Post Next Post