我有两张 table 。如果我从 table1 中删除一条记录,那么第一个查询应该检查它的 pk 是否作为 table2 中的外键存在,然后它不应该删除该记录,否则它应该删除。
我使用了这个但抛出语法错误
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
更新:
根据下面的答案,我已经这样做了,它是否正确?
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
最佳答案
也许像这样?
DELETE FROM Setup.IncentivesDetail
WHERE Setup.IncentivesDetail.IncentivesDetailID= @IncentivesDetailID
AND NOT EXISTS(SELECT 1 FROM Employee.IncentivesDetail WHERE IncentiveDetail_ID= @IncentivesDetailID)
但我必须承认,这闻起来有点......你是在做清理工作还是这是你经常做的事情?
关于sql - 如果记录作为外部表存在于另一个表中,如何不删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982670/