Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Delete Using Inner Joins

The following SQL statement executes fine on my database:

SELECT * FROM tblKPIs AS k 
INNER JOIN tblKeyPointLinks AS l ON k.KPIID = l.KPIID 
INNER JOIN tblKeyPoints AS p ON p.KptID = l.KptID 
INNER JOIN tblHistory AS h ON h.HistoryID = p.HistoryID 
WHERE h.CaseNo = 50043;

Yet the equivalent Delete statement gives an error 'syntax near AS'?

DELETE FROM tblKPIs AS k 
INNER JOIN tblKeyPointLinks AS l ON k.KPIID = l.KPIID 
INNER JOIN tblKeyPoints AS p ON p.KptID = l.KptID 
INNER JOIN tblHistory AS h ON h.HistoryID = p.HistoryID 
WHERE h.CaseNo = 50043;

Can I not use Joins in Delete statements?

If not how do I perform the above Delete?

EDIT

The table tblKeyPointLinks is an intermediate table to establish a many-to-many relationship between tblKPIs and tblKeyPoints. Therefore the SELECT statement returns some of the entries in tblKPIs more than once. Is this why the DELETE statement is having problem perhaps? What is the best way to work around this?

like image 478
PJW Avatar asked Nov 03 '25 19:11

PJW


1 Answers

Yes you can JOIN in delete statements:

DELETE k FROM tblKPIs AS k 
INNER JOIN tblKeyPointLinks AS l ON k.KPIID = l.KPIID 
INNER JOIN tblKeyPoints AS p ON p.KptID = l.KptID 
INNER JOIN tblHistory AS h ON h.HistoryID = p.HistoryID 
WHERE h.CaseNo = 50043;
like image 60
Igor Borisenko Avatar answered Nov 05 '25 15:11

Igor Borisenko