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

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

我有两张 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/

相关文章:

sql-server-2008 - 当前事务无法提交,不支持写入日志文件的操作。回滚事务

mysql - 选择摘录?

SQL Server 2005 动态选择

mysql - 使用子查询 select 获取列值

sql-server - 在表值函数中使用命名参数

sql-server - Entity Framework 和 SQL Server 优化顾问

SQL Server 2008 中 Delphi TClientDataSet "Trying to modify read-only field"错误,2000 中正常

sql - SQL Server 转换失败

php - SQL 数组上的多查询失败

mysql - 如何使用递归公用表表达式删除结果?