摘要:最近工作要编写一些SQL的存储过程,略做整理,只是一些小小的知识碎片。今天整理的是SQL中的异常处理问题。
下文中我除去了一些完整的使用方法,只做定义,打开操作(cursor, xml handler),这里只是写异常问题。
代码片段:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
/* ==========================================================================
| SP NAME : sp Name
| PURPOSE :
|
| RETURN :
|
|
| ASSUME :
| HISTORY :
===========================================================================*/
ALTER PROCEDURE SP_Name
@xml_msg xml
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
/* xml_handler*/
DECLARE @xml_handler INT
EXEC sp_xml_preparedocument @xml_handler OUTPUT, @xml_msg
/* cursor */
DECLARE cur CURSOR FOR SELECT * from table
OPEN cur
END TRY
BEGIN CATCH
/* step 1*/
print error_state()
print error_message()
print error_line()
/* step 2 deal xml handler*/
if @xml_handler > 0
exec sp_xml_removedocument @xml_handler
set @xml_handler = 0
/* step 3 deal cursor*/
IF cursor_status('global','cur') >= 0
BEGIN
--close cur
CLOSE cur
--delete cur
DEALLOCATE cur
END
/*step 4 the special error SP*/
exec generic_error_handler
END CATCH
END
具体步骤
首先通过try。。。。catch方式捕捉异常
step 1 通过一些SQL自带的函数,来捕捉一些有用的错误信息
比如:
print error_state() 返回错误状态代码
print error_message() 返回错误完整信息
print error_line() 返回错误位置
step 2,3 处理一些可能没有关闭的句柄,这些句柄将会耗费占用不必要的内存
step 4 使用一些专门处理错误的SP。