sql 示例使用SQL try catch进行错误处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 示例使用SQL try catch进行错误处理相关的知识,希望对你有一定的参考价值。

-- Running same code out of procedure will work (read: it will fail only once), because ERROR_PROCEDURE is NULL and entire evaluation of @ErrorMessage will result in NULL
BEGIN TRY
	-- let's do something
	--  ...
	-- Exception happens
	PRINT 0/0
END TRY

BEGIN CATCH
	DECLARE @ErrorMessage VARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SELECT 
		@ErrorMessage = ERROR_MESSAGE() + ' Procedure '+ ERROR_PROCEDURE() + ' Line: '+ERROR_LINE(),
		@ErrorState = ERROR_STATE();
	RAISERROR (@ErrorMessage,16,@ErrorState);
END CATCH
-- Output
-- Msg 50000, Level 16, State 1, Line 16
-- This procedure will fail twice, first time in main TRY block and second time in CATCH statement because of converting ERROR_MESSAGE to INT
CREATE PROCEDURE dbo.SomeWork
AS
BEGIN TRY
	-- let's do something
	--  ...
	-- Exception happens
	PRINT 0/0
END TRY

BEGIN CATCH
	DECLARE @ErrorMessage VARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SELECT 
		@ErrorMessage = ERROR_MESSAGE() + ' Procedure '+ ERROR_PROCEDURE() + ' Line: '+ERROR_LINE(),
		@ErrorState = ERROR_STATE();
	RAISERROR (@ErrorMessage,16,@ErrorState);
END CATCH
GO
EXEC dbo.SomeWork
-- Output:
-- Msg 245, Level 16, State 1, Procedure SomeWork, Line 14
-- Conversion failed when converting the nvarchar value 'Divide by zero error encountered. Procedure SomeWork Line: ' to data type int.

以上是关于sql 示例使用SQL try catch进行错误处理的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 try-catch 处理 SQL 异常 [重复]

TRY/CATCH 块与 SQL 检查

T-SQL 抛出异常并返回(不使用 TRY)

sql try/catch rollback/commit - 防止回滚后的错误提交

MSSQL之try Catch的用法通俗讲解

用于 SQL 插入的 PHP Try and Catch