Let me explain you the question first. Consider the Employees and Departments tables below.
To do this we will write a query using joins as shown below.
Select E.Name as [Employee Name],D.Name as [Department Name]
from Employees E
Inner Join Departments D
On E.DeptId = D.Id
Where D.Name = 'HR'
Now I want you to write a query, that deletes all the HR department employees. To do this we have to join Employees and Departments tables and usually we will be tempted to write the query as shown below, but this query will not execute and will give a syntax error.
Incorrect SQL Delete Query to delete from multiple tables invloved in a SQL join
Delete From Employees E
Inner Join Departments D
On E.DeptId = D.Id
Where D.Name = 'HR'
The query below shows the correct syntax for issuing a SQL delete that involves a SQL join.
Delete E From (Employees E
Inner Join Departments D
On E.DeptId = D.Id
and D.Name = 'HR')
The following syntax is also valid and has the same effect.
Delete Employees From
(
Employees join Departments
on Employees.DeptId = Departments.Id
)
where Departments.Name = 'HR'
how to delete duplicate records from table.
ReplyDeleteUsing CTC statement in Sql Server
Deletewith tbltem as(
Select Row_Number() over(Partition by Name order by Name) as RowNumber,* from Employee)Delete from tbltem where RowNumber>1
delete Employees
ReplyDeletefrom Employees
t1 inner join Departments t2 on t1.DeptId = t2.Id
where t2.Name = 'HR'
@Anonymous May 13, 2013 at 1:20 PM:
ReplyDeleteYour query deletes all the matched records. But in the case where more than one of the same record if exists, deletion should be done leaving one record. In that case how should we perform deletion?
Some Friend asking about duplicate deletion.
ReplyDeleteI think, Check your relation could be irrelevant or your joining could have mistake if you are working with Relation.
what if the table you tent to delete are been referenced by other objects ?
ReplyDelete