如果记录在另一个表中作为外来记录存在,如何不删除?

时间:2016-03-14 08:29:27

标签: sql sql-server sql-server-2008 tsql

我有2张桌子。如果我从table1中删除一条记录,那么第一个查询应检查它的pk是否作为表2中的外键存在,那么它不应该删除它应该的记录。

我使用了这个,但抛出了语法错误

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

2 个答案:

答案 0 :(得分:2)

也许是这样的?

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

但我必须承认,这个闻起来有点......你在干净吗?或者这是你正在做的事情吗?

答案 1 :(得分:1)

您所描述的是外键约束的定义 如果这些表之间已有外键,请确保 标记为ON DELETE CASCADE
如果是,则应将其删除并重新创建,ON DELETE CASCADE请参阅this link from MSDN了解详细信息。
如果您还没有外键约束,则需要创建一个:

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