I've created a MySQL function and would like to raise an error if the values passed for the parameters are invalid. What are my options for raising an error within a MySQL function?
相关问题
- Keeping track of variable instances
- What is the best way to cache a table from a (SQL)
- How to get the maximum of more than 2 numbers in V
- sqlyog export query result as csv
- how to call a C++ dll from C# windows application
In MySQL 5 you may raise an error by calling a stored procedure that does not exist (CALL raise_error) or passing an invalid value to a query (like null to a NOT NULL contrained field). Here is an interesting post by Roland Bouman on raising errors from within a MySQL function:
http://rpbouman.blogspot.com/2005/11/using-udf-to-raise-errors-from-inside.html
MySQL 5.5 introduces signals, which are similar to exceptions in other languages:
http://dev.mysql.com/doc/refman/5.5/en/signal.html
For example, in the
mysql
command line client:It's actually a combination of all three answers. You call a non-existent procedure to raise the error, and then declare an exit handler that catches the error you generated. Here's an example, using SQLSTATE 42000 (procedure does not exist) to throw an error before deletion if the row to be deleted has a foreign key id set:
Output:
Why not just store a
VARCHAR
in a declaredINTEGER
variable?Error message is:
It's not perfect, but it gives a pretty descriptive message and you don't have to write any extension DLLs.
You can also call an existing function with an invalid number of arguments.
You have to define exception handlers . Take a look at http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html