且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在SQL Server中删除之前,我可以检查约束吗?

更新时间:2022-10-21 20:27:45

  If Exists(Select * From OtherTable 
其中OtherTableFKColumn = MainTablePrimaryKey)
Begin
回滚事务
RaisError('表中的违反FK约束[OtherTable]',16,1 )
End


I have following situation. A main table and many other tables linked together with foreign keys. Now when I would like to delete a row in the main table a ConstraintsViolation will occur, which is intended and good.

Now I want to be able to check if the ConstraintsViolation will occur before I trigger the delete row event.

Is this possible?

If Exists ( Select * From OtherTable
            Where OtherTableFKColumn = MainTablePrimaryKey) 
   Begin
       Rollback Transaction
       RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1)
   End