我想知道,为什么SQL Server在执行过程中的动态SQL时无法执行error_procedure。我可以在方案2中的错误消息中调用过程名称吗?
情景1:
CREATE PROCEDURE [dbo].[TEST_PROCEDURE]
AS
BEGIN
EXEC SELECT 1/0
END
GO
EXEC TEST_PROCEDURE
错误讯息:
Msg 8134,Level 16,State 1,Procedure TEST_PROCEDURE,Line 6
除以遇到的零错误。
情景2:
CREATE PROCEDURE [dbo].[TEST_PROCEDURE]
AS
BEGIN
EXEC('SELECT 1/0')
END
GO
EXEC TEST_PROCEDURE
错误讯息:
Msg 8134,Level 16,State 1,Line 1
除以遇到的零错误。
答案 0 :(得分:0)
CREATE PROCEDURE [dbo].[TEST_PROCEDURE]
AS
BEGIN
BEGIN TRY
EXEC('SELECT 1/0')
END TRY
BEGIN CATCH
DECLARE @Err VARCHAR(255);
SELECT @Err = 'Error in TEST_PROCEDURE. ' + ERROR_MESSAGE()
RAISERROR(@Err, 16, -1)
END CATCH
END
答案 1 :(得分:0)
Use ERROR_PROCEDURE()
内置函数来获取MSSQL中的过程名称。通过添加TRY CATCH来更改您的过程,如下所示。
ALTER PROCEDURE [dbo].[TEST_PROCEDURE]
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
EXEC('SELECT 1/0')
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000)
,@ErrorSeverity INT
,@ErrorState INT
,@ErrorProcedure NVARCHAR(128)
SELECT @ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE(),
@ErrorProcedure = ERROR_PROCEDURE();
RAISERROR (@ErrorMessage,
@ErrorSeverity,
@ErrorState,
@ErrorProcedure)
END CATCH;
SET NOCOUNT OFF;
END
消息50000,级别16,状态1,过程TEST_PROCEDURE,第19行[批处理开始第2行] 除以零错误。