我想记录从我的Transact SQL脚本中抛出的警告,这些警告不会被TRY ... CATCH块捕获。有没有办法做到这一点? ERROR_NUMBER()等不会在catch块之外工作,我不知道如何知道如何知道警告被抛出。谷歌搜索没有产生太多。
答案 0 :(得分:1)
documentation似乎打算将错误消息传递给调用者。但它也说明如果将语句包装在存储过程中,然后在try-catch块中调用该语句,则会捕获低严重性错误。
-- Verify that the stored procedure does not exist.
IF OBJECT_ID ( N'usp_ExampleProc', N'P' ) IS NOT NULL
DROP PROCEDURE usp_ExampleProc;
GO
-- Create a stored procedure that will cause an
-- object resolution error.
CREATE PROCEDURE usp_ExampleProc
AS
SELECT * FROM NonexistentTable;
GO
BEGIN TRY
EXECUTE usp_ExampleProc;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
答案 1 :(得分:0)
即使将它包装在proc中并尝试,也无法通过try catch捕获这些错误。这是一个例子。
CREATE PROC P
AS
BEGIN
RAISERROR('TEST',9,-1,-1)
END;
BEGIN TRY
EXEC P
END TRY
BEGIN CATCH
PRINT 'CAUGHT'
END CATCH;