SQL ERROR_MESSAGE and SQLERRM
Error handlers need to know what failed. Each engine exposes the message and code inside its handler, under different names.
- カテゴリ
- System & session
- Returns
text (the message), integer or text (the code)- In this category
- 13 of 13
構文
ERROR_MESSAGE(), ERROR_NUMBER()
SQLERRM, SQLSTATE
SQLERRM, SQLCODE
GET DIAGNOSTICS CONDITION 1
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | ERROR_MESSAGE, ERROR_NUMBER, ERROR_LINE and friends inside BEGIN CATCH |
| PostgreSQL | Different name or syntax | SQLERRM and SQLSTATE in a PL/pgSQL EXCEPTION block |
| MySQL | Different name or syntax | GET DIAGNOSTICS CONDITION 1 @msg = MESSAGE_TEXT, also inside handlers |
| SQLite | Not built in | no procedural error handling in SQL |
| Oracle | Different name or syntax | SQLERRM and SQLCODE in a PL/SQL EXCEPTION block |
例
SQL Server
BEGIN TRY SELECT 1 / 0; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS num, ERROR_MESSAGE() AS msg; -- 8134, Divide by zero error encountered. END CATCH;
PostgreSQL
DO $$ BEGIN PERFORM 1 / 0; EXCEPTION WHEN OTHERS THEN RAISE NOTICE '% %', SQLSTATE, SQLERRM; -- 22012 division by zero END $$;
Oracle
DECLARE n NUMBER; BEGIN n := 1 / 0; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLCODE || ' ' || SQLERRM); -- -1476 ORA-01476: divisor is equal to zero END; /
MySQL
SELECT 1 FROM no_such_table; GET DIAGNOSTICS CONDITION 1 @code = MYSQL_ERRNO, @msg = MESSAGE_TEXT; SELECT @code, @msg; -- 1146 and the message
知っておくと便利なこと
- ERROR_MESSAGE() and the other ERROR_ functions return NULL outside a CATCH block.
- TRY/CATCH does not catch compile errors in the same batch, such as a misspelled column, or errors of severity 20 and above that end the connection.
- Oracle's SQLERRM includes the code ('ORA-01476: divisor is equal to zero'); PostgreSQL's SQLERRM is the bare message and SQLSTATE holds the five-character code, such as 22012.
Questions about ERROR_MESSAGE
How do I re-raise the error after logging it?
THROW; inside the CATCH block on SQL Server, RAISE; in PL/pgSQL and PL/SQL, RESIGNAL in a MySQL handler.
Does CATCH roll back the transaction?
No. Check XACT_STATE() in the CATCH block: -1 means the transaction is doomed and must be rolled back; 1 means it can still commit.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.