2014-09-29 65 views
1

我有一個存儲過程spMyProc。該過程傳遞一個表名作爲參數@TableName。在繼續執行過程之前,驗證表格是否存在非常重要。如何在SQL Server中引發自定義異常

如何在表名無效的情況下創建自定義異常來引發錯誤?

我知道TRYCATCH但我不確定如何將它們與自定義例外放在一起。

問候。

+0

哪SQL Server的**版本**?在2012年,我們得到了一個新的'THROW'關鍵字.... – 2014-09-29 15:56:44

+1

不幸的是2008!我無法等待升級到2014. – 2014-09-29 15:57:40

+1

您應該能夠使用['RAISERROR'](http://msdn.microsoft.com/zh-cn/library/ms178592.aspx)實現您的目標。聲明 – 2014-09-29 15:58:44

回答

1

我認爲這裏提供的例子之一RAISERROR應該符合你的問題。新版本的SQL Server將使用THROW而不是RAISERROR。

2

調查RAISERROR()的故事。

TRY .. CATCH工作得同樣的,因爲它會在其他任何編程語言

BEGIN TRY 

    -- do your checks 
     IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE NAME = @TableName) 
     BEGIN 
      RAISERROR('Table does not exist', 16,1) 
     END 

    -- rest of the code if checks are passed 
    -- if above checks are not passed and you riase an error 
    -- control will skip any code in TRY Block after the error has been 
    -- Raised and staright jump to Catch block. 

END TRY 

BEGIN CATCH 
    -- Do your error logging 
    -- Other stuff 
    -- you have access to ERROR_ functions here to get detailed info about errors 
END CATCH 
1

您可以使用嘗試捕捉和RAISEERROR用於處理自定義異常工作,例如:

begin try 
    --sql statements 
end try 
begin catch 
    RAISERROR 
    (
    ERROR_MESSAGE(), -- or add your custom message 
    ERROR_SEVERITY(), 
    1,    
    ERROR_NUMBER(), -- parameter: original error number. 
    ERROR_SEVERITY(), -- parameter: original error severity. 
    ERROR_STATE(),  -- parameter: original error state. 
    ISNULL(ERROR_PROCEDURE(), '-'), -- parameter: original error procedure name. 
    ERROR_LINE()  -- parameter: original error line number. 
end catch