我有一个调用多个其他存储过程的存储过程。如果存储过程遇到错误,它是退出还是继续执行其余代码?
如何确保如果一个部分失败,则会打印失败的存储过程并继续执行下一个部分。
E.g
"spInsert_1 fail"
"spInsert_2 sucess"
代码:
CREATE PROCEDURE [dbo].[spInsertAll]
AS
BEGIN
SET NOCOUNT ON;
exec dbo.spInsert_1
exec dbo.spInsert_2
exec dbo.spInsert_3
END
答案 0 :(得分:1)
从技术上讲,SQL Server默认会为您执行此操作 - 但您可能希望以更优雅的方式执行此操作。这是方式
存储过程1
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp1]
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT 1
PRINT 'SP1 is completed'
END TRY
BEGIN CATCH
PRINT 'SP 1 is Failed'
END CATCH'
END
存储过程2 (将生成错误)
CREATE PROCEDURE [dbo].[sp2]
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT 1/0
PRINT 'SP2 is completed'
END TRY
BEGIN CATCH
PRINT 'SP 2 is Failed'
END CATCH
END
存储过程3
CREATE PROCEDURE [dbo].[sp3]
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
SELECT 1
PRINT 'SP 3 is completed'
END TRY
BEGIN CATCH
PRINT 'SP 3 is Failed'
END CATCH
END
主存储过程
CREATE PROCEDURE dbo.Mainsp
AS
BEGIN
SET NOCOUNT ON;
EXEC dbo.sp1
EXEC dbo.sp2
EXEC dbo.sp3
END
GO
执行主程序时的消息
SP 1 is completed
SP 2 is Failed
SP 3 is completed
即使您不使用TRY-CATCH,SQL也会以所需的方式执行存储过程。您将看到的唯一区别是成功/失败消息。