尽管进行了伪造数据测试,SQL 2005 try / catch块永远不会达到'catch'

时间:2010-02-08 22:25:11

标签: sql-server-2005 try-catch

好的,我不熟悉SQL 2005错误处理和我 学习try / catch语句。

我写过以下程序,但无论我传递给它, 我的ErrorLog表中从未有任何数据。我已通过所有INT 值,所有日期时间值或不在DB中的数据字符串 并且在ErrorLog中没有报告任何内容的情况下获得'0行影响'。它是 好像永远不会达到CATCH声明(为了它的价值,我 也尝试在顶部评论验证。

任何想法我做错了什么?感谢。

ALTER PROCEDURE [dbo].[aspnet_Membership_UpdateLastActivityDate]   

@UserId nvarchar(256),
@UserName nvarchar(256),
@LastActivityDate datetime,
@ApplicationName nvarchar(256)

AS

DECLARE @Today DATETIME
DECLARE @MSG VARCHAR(255)
DECLARE @Severity INT
DECLARE @ErrorCode INT

BEGIN

SET XACT_ABORT ON   -- (I have also tried it without XACT_ABORT. No difference)

BEGIN TRY

    SET @ErrorCode = 0
    SELECT @Today = GetDate()

    IF (@UserId IS NULL)
    RETURN(1)

    IF (@UserName IS NULL)
    RETURN(1)

    IF (@LastActivityDate IS NULL)
    RETURN(1)

    BEGIN TRAN
        UPDATE dbo.aspnet_Users WITH (ROWLOCK)
        SET LastActivityDate = @LastActivityDate
        FROM dbo.aspnet_Users u
        INNER JOIN dbo.aspnet_Applications a
        ON u.ApplicationId = a.ApplicationId
        WHERE u.UserName = @UserName
        AND u.UserId = @UserId
        AND a.ApplicationName = @ApplicationName
    COMMIT TRAN

END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK TRAN   

    SET @ErrorCode = Error_Number()
    SET @Severity = Error_Severity()
    SET @MSG = 'An error was thrown: '
        + 'Error(' + @ErrorCode + '):' + ERROR_MESSAGE()
        + ' Severity = ' + ERROR_SEVERITY() 
        + ' State = ' + ERROR_STATE()
        + ' Procedure = ' + ERROR_PROCEDURE()
        + ' Line Number = ' + ERROR_LINE()

    INSERT INTO [dbo].[ErrorLog]([errornum], [errortype], [errormsg],[errorsource], [errordate])
    VALUES (@ErrorCode, 'E', @MSG, Error_Procedure(), @Today)

    RAISERROR(@MSG, @Severity, 2)

END CATCH

END

RETURN @ErrorCode

2 个答案:

答案 0 :(得分:2)

我已经做了很多SQL错误处理,但是我没有看到任何可能产生错误的地方。你是否期望“回归”声明被“抓住”?这不会发生......他们只会从函数返回。您需要引发错误,而不是触发返回。

答案 1 :(得分:2)

同意@Mark。尝试更改此内容:

IF (@UserId IS NULL)
    RETURN(1)

对此:

IF (@UserId IS NULL)
BEGIN
    RAISERROR('No UserID was passed in.', 11, 1);
    RETURN 1;
END

另请参阅本文,了解Erland Sommarskog的错误处理入门:

http://www.sommarskog.se/error_handling_2005.html