MySQL Error: Updates Prohibited Within Stored Functions/Triggers
When attempting to update a table within a MySQL stored function or trigger, you may encounter the error:
Error: Can't update table 'brandnames' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
Understanding the Error
This error stems from the restriction in MySQL that prohibits modifying a table while an INSERT trigger is executing. Such modifications could potentially lead to deadlocks or infinite recursive loops.
Avoiding the Error
To avoid this error, consider the following approaches:
Use NEW and OLD Fields:
Modify the Trigger Context:
Example Using BEFORE INSERT Trigger:
Suppose you have a full_brand_name field and need to create a short_name field containing the first two letters in uppercase:
CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames` FOR EACH ROW BEGIN SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_brand_name,1)) , LCASE(SUBSTRING(NEW.full_brand_name,2))) END
The above is the detailed content of Why Can't I Update a Table Inside a MySQL Stored Function or Trigger?. For more information, please follow other related articles on the PHP Chinese website!