Delete multiple table data using transaction block, table variable and JOIN.
BEGIN TRANSACTION;
declare @deletedIds table ( id int );
DELETE w
output deleted.EmployeeRun into @deletedIds
FROM WorkRecord2 w
INNER JOIN Employee e
ON e.EmployeeNo = w.EmployeeRun
AND w.Company = 1
AND w.date = '2013-05-06';
DELETE e
FROM Employee as e
INNER JOIN @deletedIds as d
ON d.id = e.EmployeeNo;
COMMIT TRANSACTION;
Please check from url https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=43330dda6f1b71b8ec4172a24d5b6921
Delete multiple table data with temporary table and JOIN. Drop temporary table after deletion.
BEGIN TRANSACTION;
-- create temporary table
create table #deletedRecords (employeeId int);
-- INSERT INTO #deletedRecords
SELECT e.EmployeeNo
FROM WorkRecord2 w
INNER JOIN Employee e
ON e.EmployeeNo = w.EmployeeRun
AND w.Company = 1
AND w.date = '2013-05-06';
-- delete from WorkRecord2
DELETE w
FROM WorkRecord2 w
INNER JOIN #deletedRecords d
ON w.EmployeeRun = d.employeeId;
-- delete from Employee using exists
DELETE
FROM Employee
WHERE EXISTS (SELECT 1
FROM #deletedRecords d
WHERE d.employeeId = EmployeeNo);
-- drop temporary table
DROP TABLE #deletedRecords;
COMMIT TRANSACTION;
Please check from url https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=d52c6c1ed91669d68fcc6bc91cb32d78
Alternative way to create temporary tables by using SELECT INTO
BEGIN TRANSACTION;
SELECT e.EmployeeNo employeeId
INTO #deletedRecords
FROM WorkRecord2 w
INNER JOIN Employee e
ON e.EmployeeNo = w.EmployeeRun
AND w.Company = 1
AND w.date = '2013-05-06';
-- delete from WorkRecord2
DELETE w
FROM WorkRecord2 w
INNER JOIN #deletedRecords d
ON w.EmployeeRun = d.employeeId;
-- delete from Employee using exists
DELETE
FROM Employee
WHERE EXISTS (SELECT 1
FROM #deletedRecords d
WHERE d.employeeId = EmployeeNo);
-- drop temporary table
DROP TABLE #deletedRecords;
COMMIT TRANSACTION;
Please check from url https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=0f02f05616ce5b4dcc8fc67c6cf1e640
Remove a single table data using JOIN
DELETE w
FROM WorkRecord2 w
INNER JOIN Employee e
ON e.EmployeeNo = w.EmployeeRun
AND w.Company = 1
AND w.date = '2013-05-06'
Please check from url https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=84a60d1368556a8837281df36579334a
Delete single table data using CTE
WITH cte AS (
SELECT w.EmployeeRun
FROM WorkRecord2 w
WHERE EXISTS (SELECT 1
FROM Employee
WHERE EmployeeNo = w.EmployeeRun)
AND w.Company = 1
AND w.date = '2013-05-06'
)
DELETE
FROM cte
Please check from url https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=6590007b3c8c2ffad5563bd86606c5b1
Use ON CASCADE DELETE during foreign key creation in child table. If remove parent table data then corresponding child table data is automatically deleted.
DELETE
with a join