中止外键约束违规的存储过程

时间:2011-11-03 10:38:42

标签: sql-server stored-procedures

如果由于外键约束违规而无法成功执行删除语句,是否有办法在SQL Server中中止存储过程?默认情况下,该过程似乎忽略该错误并继续下一个语句。

但是,对于其他类型的错误(例如,从不存在的表中删除),过程将中止。

示例程序:

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE  [dbo].[TestSP]
AS
BEGIN
    SET NOCOUNT ON;

    print 'BEFORE';

    DELETE FROM ExistingWithConstraints;
    print 'AFTER DELETE ExistingWithConstraints';

    DELETE FROM NonExisting;
    print 'AFTER DELETE NonExisting';
END

生成输出(请注意,上面的最后一条消息不打印):

BEFORE
<snip constraint violation error message>
AFTER DELETE ExistingWithConstraints    
<snip invalid object name error message>

2 个答案:

答案 0 :(得分:3)

使用交易和正确的错误处理

CREATE PROCEDURE  [dbo].[TestSP]
AS
SET XACT_ABORT, NOCOUNT ON
DECLARE @starttrancount int

BEGIN TRY
    SELECT @starttrancount = @@TRANCOUNT

    IF @starttrancount = 0
        BEGIN TRANSACTION

    DELETE FROM ExistingWithConstraints;
    DELETE FROM NonExisting;

    IF @starttrancount = 0 
        COMMIT TRANSACTION
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 AND @starttrancount = 0 
        ROLLBACK TRANSACTION
    RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
END CATCH
GO

这是基于我的回答:Nested stored procedures containing TRY CATCH ROLLBACK pattern?

答案 1 :(得分:-1)

执行继续允许您检查@@ ERROR标准变量是否存在问题。一种更现代的方法,虽然它使用2005年添加到SQL的TRY..CATCH块:

http://msdn.microsoft.com/en-us/library/ms179296.aspx