If I have a trigger
before the update
on a table, how can I throw an error that prevents the update on that table?
相关问题
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Flush single app django 1.9
Here is one hack that may work. It isn't clean, but it looks like it might work:
Essentially, you just try to update a column that doesn't exist.
Another (hack) method (if you are not on 5.5+ for some reason) that you can use:
If you have a required field, then within a trigger set the required field to an invalid value such as NULL. This will work for both INSERT and UPDATE. Do note that if NULL is a valid value for the required field (for some crazy reason) then this approach will not work.
If you are on 5.5+ then you can use the signal state as described in other answers:
Unfortunately, the answer provided by @RuiDC does not work in MySQL versions prior to 5.5 because there is no implementation of SIGNAL for stored procedures.
The solution I've found is to simulate a signal throwing a
table_name doesn't exist
error, pushing a customized error message into thetable_name
.The hack could be implemented using triggers or using a stored procedure. I describe both options below following the example used by @RuiDC.
Using triggers
Using a stored procedure
Stored procedures allows you to use dynamic sql, which makes possible the encapsulation of the error generation functionality in one procedure. The counterpoint is that we should control the applications insert/update methods, so they use only our stored procedure (not granting direct privileges to INSERT/UPDATE).
The following procedure is (on mysql5) a way to throw custom errors , and log them at the same time:
As of MySQL 5.5, you can use the
SIGNAL
syntax to throw an exception:State 45000 is a generic state representing "unhandled user-defined exception".
Here is a more complete example of the approach: