2016-03-08 81 views
1

以下是在我試圖捕獲異常的過程中,如果有任何存儲過程異常使用TRY CATCH存儲過程

DROP PROCEDURE IF EXISTS test; 

DELIMITER // 

CREATE PROCEDURE test(IN contextFilter TEXT) 
    BEGIN TRY 


    set @sub_query = 'SELECT id from test_table'; 

    PREPARE stmt_query FROM @sub_query; 
     SELECT @sub_query; 
       EXECUTE stmt_query; 
       DEALLOCATE PREPARE stmt_query; 

    END TRY // 
    BEGIN CATCH 
    SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_MESSAGE() AS ErrorMessage; 
    END CATCH 

DELIMITER ; 

當我嘗試源的存儲過程,我是獲得以下例外

source /home/test.sql; 
Query OK, 0 rows affected (0.01 sec) 

ERROR 1064 (42000) at line 5 in file: '/home/test.sql': You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'set @sub_query = 'SELECT id from test_table'; 

    PREPARE stmt_query FROM @' at line 5 
ERROR 1064 (42000) at line 17 in file: '/home/test.sql': You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CATCH 
    SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_MESSAGE() AS ErrorMessage; 
' at line 1 
+0

您可以使用[13.6.7.5 SIGNAL語法](http://dev.mysql.com/doc/refman/5.7/en/signal.html)。 – wchiquito

回答

1

在mySql中,沒有類似於Java的try... catch塊。你可以通過錯誤處理來處理錯誤嗎?

語法

DECLARE handler_action HANDLER 
    FOR condition_value [, condition_value] ... 
    statement 

handler_action: 
    CONTINUE 
    | EXIT 
    | UNDO 

condition_value: 
    mysql_error_code 
    | SQLSTATE [VALUE] sqlstate_value 
    | condition_name 
    | SQLWARNING 
    | NOT FOUND 
    | SQLEXCEPTION 

的handler_action值指示處理程序語句執行後的處理程序採取什麼樣的行動:

CONTINUE:當前程序的繼續執行。

EXIT:執行終止於聲明處理程序的BEGIN ... END複合語句。即使條件出現在內部塊中也是如此。

UNDO:不支持。

欲瞭解更多信息請訪問網站Official