首页 > 数据库 > 文库 > 正文

SQL存储过程中运用BEGIN TRY捕捉错误并保存

2024-09-07 22:12:44
字体:
来源:转载
供稿:网友
       SQL存储过程中使用BEGIN TRY捕捉错误并保存:

         1、创建保存错误的数据表:
 
      /*创建错误日志表*/
       CREATE TABLE ErrorLog(
                                            errNum INT,
                                            ErrSev NVARCHAR(500),
                                            ErrState INT,
                                            ErrProc NVARCHAR(1000),
                                            ErrLine INT,
                                            ErrMsg NVARCHAR(2000)
                                            )
      2、创建保存错误信息的存储过程:
 
       /*创建错误日志记录存储过程*/
CREATE PROCEDURE InsErrorLog
AS
BEGIN
        INSERT INTO ErrorLog
             SELECT  ERROR_NUMBER() AS ErrNum,
                             ERROR_SEVERITY()AS ErrSev,
                             ERROR_STATE() AS ErrState,
                             ERROR_PROCEDURE() AS ErrProc,
                             ERROR_LINE()AS ErrLine,
                             ERROR_MESSAGE()AS ErrMsg
END
3、在存储过程中使用BEGIN TRY,并捕捉错误保存:
 
CREATE PROCEDURE GetErrorTest
AS
BEGIN TRY
   /*在这里填写存储过程的内容*/
     ***
END TRY
BEGIN CATCH
    EXEC InsErrorLog --调用 InsErrorLog 存储过程,保存错误日志
END CATCH 

(编辑:武林网)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表