How not to delete if the record exists as foreign in another table?

I have 2 tables. If I delete a record from table1, then the first query should check if pk exists as a foreign key in table2, then it should not delete the record that it should.

I used this error, but throwing syntax

DELETE FROM Setup.IncentivesDetail
INNER JOIN Employee.IncentivesDetail ON Setup.IncentivesDetail.IncentivesDetailID = Employee.IncentivesDetail.IncentiveDetail_ID
WHERE Setup.IncentivesDetail.IncentivesDetailID= @IncentivesDetailID
    AND Employee.IncentivesDetail.IncentiveDetail_ID= @IncentivesDetailID

UPDATE:

Based on the answers below, I did this, is this correct?

If Not Exists(Select * from Employee.IncentivesDetail where IncentivesDetail.IncentiveDetail_ID= @IncentivesDetailID)
        Begin
            Delete from Setup.IncentivesDetail
            WHERE Setup.IncentivesDetail.IncentivesDetailID= @IncentivesDetailID
        End
        Else
        Begin
            RAISERROR('Record cannot be deleted because assigned to an employee',16,1) 
            RETURN  
        End
+4
source share
2 answers

Maybe so?

DELETE FROM Setup.IncentivesDetail
WHERE Setup.IncentivesDetail.IncentivesDetailID= @IncentivesDetailID
  AND NOT EXISTS(SELECT 1 FROM Employee.IncentivesDetail WHERE IncentiveDetail_ID= @IncentivesDetailID) 

But I have to admit, it smells a little ... Are you doing a cleanup or is it something you do regularly?

+2
source

, , - .
, , ON DELETE CASCADE.
, ON DELETE CASCADE . MSDN. , :

ALTER TABLE Setup.IncentivesDetail 
ADD CONSTRAINT FK_Setup_IncentivesDetail_IncentivesDetailID FOREIGN KEY (IncentivesDetailID) 
    REFERENCES Employee.IncentivesDetail (IncentiveDetail_ID ) 
;
+1

All Articles