如何获取DEFAULT ERROR消息以及Custom RAISERROR消息

时间:2013-10-11 18:25:01

标签: sql-server tsql stored-procedures sql-server-2008-r2

您好我正在使用SQL SERVER 2008 R2数据中心版,我有这个存储过程,我使用raiserror引发自定义错误消息。有没有办法得到sql server的defualt错误消息。存储过程的代码如下。

CREATE Procedure usp_SomeName
@StableName         nvarchar(50) = NULL,
@StableID           INT = NULL OUTPUT,
@StableDescription ntext = NULL,
@Picture            image = NULL,
@ReturnCode         int = NULL OUTPUT,
@ReturnMessage      nvarchar(100) = NULL OUTPUT
AS
BEGIN
  SET NOCOUNT ON;
    BEGIN TRY

           IF @StableName IS NULL
             RAISERROR('Validation Failed: Stable name cannot be null', 16,1)

           IF EXISTS (SELECT StableName from dem.TableName
                        WHERE StableName = @StableName)
              RAISERROR('Validation Failed: Stable Name already Exists',16,1)

        BEGIN TRANSACTION
          INSERT INTO TableName(StableName, [Description], Picture)
          VALUES (@StableName, @StableDescription, @Picture)

          COMMIT TRANSACTION
        SELECT @ReturnCode = 0 , @ReturnMessage = 'Sucess! New Stable Details has added.'
        SELECT @StableID = SCOPE_IDENTITY()
    END TRY

    BEGIN CATCH 
       IF (@@TRANCOUNT > 0)
         ROLLBACK TRAN

       SELECT @ReturnCode = ERROR_NUMBER(), @ReturnMessage = ERROR_MESSAGE()

          SELECT @ReturnCode AS ReturnCode, @ReturnMessage AS ReturnMessage,
                 ERROR_LINE()   AS ErrorLine,
                 ERROR_SEVERITY() AS ErrorSeverity,
                 ERROR_STATE() AS ErrorState
    END CATCH

   SET NOCOUNT OFF;
END

GO

1 个答案:

答案 0 :(得分:0)

您可以使用try catch,当您引发错误时,批处理将转到catch,然后使用@@ error_message查看错误消息。