尝试使用ALTER TABLE捕获SQL Server 2005

时间:2012-02-07 14:16:02

标签: sql sql-server-2005 try-catch

我正在尝试使用约束来改变一些表,对于生产环境,我需要某种具有“打印”功能的Try / Catch,而不是公共sql errores。我怎样才能做到这一点?我试过这个:

BEGIN TRY
My command
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

但它不起作用。我将表的名称更改为不存在的名称,结果是典型的消息。

提前致谢

我的来源:http://msdn.microsoft.com/en-us/library/ms178592%28v=sql.90%29.aspx

1 个答案:

答案 0 :(得分:2)

它在我的comp中起作用

另外,为什么不使用打印消息?

enter image description here

修改

根据微软的说法:

这是try catch + transaction应与:

一起使用的模式
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;