Created TRIGGER for two tables but getting error message - mysql

I have 2 tables:
ORDERS - Stores all the information from my shopping cart
ITEMS - Stores id | scode | product | price | saleprice | inventory
I have come up with the trigger below, when an order is inserted into the database in 'orders' I want it to update the 'inventory' quantity by -1 in the 'items table'.
CREATE TRIGGER `order_updater` AFTER INSERT ON `orders`
FOR EACH ROW UPDATE items
SET inventory = inventory - 1
WHERE id = new.id
END;
When I try to add it in triggers in phpMyAdmin I keep getting this message:
One or more errors have occured while processing your request:
The following query has failed: "CREATE TRIGGER orer_update BEFORE INSERT ON items FOR EACH ROW CREATE TRIGGER order_updater AFTER INSERT ON orders FOR EACH ROW UPDATE items SET inventory = inventory - 1 WHERE id = new.id END;"
MySQL said: #1303 - Can't create a TRIGGER from within another stored routine.
Can this be done with this trigger?
Will the trigger update a particular item or all items?
Can the trigger be added to the products .htm page or does it need to be in phpMyAdmin?
I'm not sure if the the code is quite right as I'm new to this, any pointers would be appreciated.
*UPDATE:
phpMyAdmin : I copied this from page it says: Version information: 4.0.8, latest stable version: 4.0.9*

Try something like:
DELIMITER $$
CREATE TRIGGER `order_updater` AFTER INSERT ON `orders`
FOR EACH ROW
BEGIN
UPDATE `items`
SET `inventory` = `inventory` - 1
WHERE `id` = new.`id`;
END$$
DELIMITER ;
UPDATE
What version of phpMyAdmin are you using? The following example, using version phpMyAdmin 4.1.0-beta2, works without problem.

Related

Unable to create a MySQL/MariaDB Stored Procedure

I have a XML file which contains 200k records. I have to insert or update the records in the database. My database structure is as followed:
+----+------+-------+-----+-----+------------+
| Id | name | stock | sku | ean | updated_by |
+----+------+-------+-----+-----+------------+
For inserting the records i'm using Doctrine. But it takes to long before all records are inserted or updated. Therefore I want to create a stored procedure.
I tried the following stored procedure but it's not working.
delimiter $$
create trigger insert
before insert on Product
for each row
begin
IF(exists(select 1 From Product WHERE sku = new.sku))
THEN
BEGIN
UPDATE Product SET stock = new.stock WHERE sku = sku;
END;
END IF;
end$$
delimiter
Error:
General error: 1442 Can't update table 'Product' in stored
function/trigger because it is already used by statement which invoked
this stored function/trigger
Update:
You can't use a MySQL trigger in the way you describe. You can't update the table for which the trigger is defined. It would result in an infinite loop.
Even if the trigger code you wrote worked, MySQL does not support "instead of" triggers. That is, it would do the UPDATE but then it would also attempt the INSERT. So it would either create another row with the same sku value, or else if you have a unique constraint on sku, the insert would cause an error and roll back both the INSERT and the UPDATE run from the trigger.
This is why the REPLACE and INSERT...ON DUPLICATE KEY UPDATE statements exist.
I understand you want to use ORM methods for all operations, but this will be a good example of a general rule: ORM's do not support all operations. Inevitably you will encounter a case where you have to write SQL if you want to do something special. Doctrine, like all ORM libraries, supports a way to run literal SQL statements, bypassing the ORM methods.
See Doctrine: ON DUPLICATE KEY UPDATE for example.
You should use insert on duplicate
but your trigger should be li9ke this
your first insert must be the trigger name and the end is missing a ;
delimiter $$
create trigger insert_prodzct
before insert on Product
for each row
begin
IF(exists(select 1 From Product WHERE sku = new.sku))
THEN
BEGIN
UPDATE Product SET stock = new.stock WHERE sku = sku;
END;
END IF;
end$$
delimiter ;

PHPmyAdmin mySQL Trigger: Upddate the parent table when child table was inserted, updated or deleted

I need some help with getting the syntax right to define a trigger in PHPmyAdmin.
What I have:
2 tables - invoice and invoiceitem
tbl_invoice has a field 'Total' which should show the sum of the 'Extended' price of the table invoiceitem
tbl_invoiceitem has 2 triggers that update the 'Extended' before_insert and before_update
What I try to accomplish:
Calculate the sum of all items for an invoice and update the 'Total' price in tbl_invoice after either new items are inserted or if the price or quantity for an existing item was updated.
I try to do this in PHPmyAdmin.
The error message is
I hope somebody can give mt a hint into the right direction. Just started with triggers and don't seem to find solution with a couple of days searching the internet.
Thank you for help in advance.
Cheers, Oliver
I can see 2 syntax errors in your code:
The delimiter commands should be outside of the trigger definition, not inside of it. Phpmyadmin should take care of this.
The commands within the begin ... end block should be terminated by semicolon (;), not by whatever you provide in the delimiter command.
I did not check if your sql commands within the trigger make sense, but the where condition of the set command does not seem right.
Ok, found a work around:write the full create trigger statement in a file and import with PHPmyAdmin. As 'Shadow' pointed out there was also a problem in the where conditions.
Below the corrected triggers that worked in my scenario.
There is a lot of examples on the net to get triggers done with the mysql client. This way you can use the exact syntax that you would type into a client and than import into PHPmyAdmin in case you can't reach the server your using with a command shell client.
Hope this helps other newbies.
Cheers, Oliver
-- after_insert trigger for InvoiceItem to Calculate the Total in Invoice
------------------------------------------------------------------------
DELIMITER //
CREATE TRIGGER `InvoiceItem_After_Insert` AFTER INSERT ON `invoiceItem`
FOR EACH ROW
BEGIN
SET #InvoiceNumber = NEW.InvoiceFK;
SET #ItemTotal = (SELECT SUM(Extended) FROM InvoiceItem WHERE InvoiceFk = #InvoiceNumber);
UPDATE Invoice SET Total = #ItemTotal WHERE id = #InvoiceNumber;
END
//
DELIMITER ;
-- after_update trigger for InvoiceItem to Calculate the Total in Invoice
------------------------------------------------------------------------
DELIMITER //
CREATE TRIGGER `InvoiceItem_After_Update` AFTER UPDATE ON `invoiceitem`
FOR EACH ROW
BEGIN
SET #InvoiceNumber = NEW.InvoiceFK;
SET #ItemTotal = (SELECT SUM(Extended) FROM InvoiceItem WHERE InvoiceFk = #InvoiceNumber);
UPDATE Invoice SET Total = #ItemTotal WHERE id = #InvoiceNumber;
END
//
DELIMITER ;
-- after_delete trigger for InvoiceItem to Calculate the Total in Invoice
----------------------------------------------------------------------
DELIMITER //
CREATE TRIGGER `InvoiceItem_After_Delete` AFTER DELETE ON `invoiceItem`
FOR EACH ROW
BEGIN
SET #InvoiceNumber = OLD.InvoiceFK;
SET #ItemTotal = (SELECT SUM(Extended) FROM InvoiceItem WHERE InvoiceFk = #InvoiceNumber);
UPDATE Invoice SET Total = #ItemTotal WHERE id = #InvoiceNumber;
END
//
DELIMITER ;
-----------------------------------------------------------------
The next 2 triggers are just single statement and are calculate the 'Extended' column in the InvoceItem table
---------------------------------------------------------------------
-- Calculate new 'Extended' price before insert
CREATE TRIGGER `InvoiceItem_Before_Insert` BEFORE INSERT ON `invoiceitem`
SET NEW.Extended = ROUND(NEW.Quantity * NEW.Price,2)
-------------------------------------------------------------------
-- Calculate new 'Extended' price before update
CREATE TRIGGER `InvoiceItem_Before_Update` BEFORE UPDATE ON `InvoiceItem`
FOR EACH ROW
SET NEW.Extended = ROUND(NEW.Quantity * NEW.Price,2);

Create Query For MYSQL Trigger

First i have 2 tables named "item" and "buy_item"
//the "stock" column is in item table and the "qty" column is ini buy_item table
then I have SQL SERVER query to create a trigger like this
CREATE TRIGGER trigger1
ON dbo.buy_item
FOR UPDATE
AS begin
UPDATE item SET stock = stock - qty FROM deleted WHERE item.id = deleted.id
UPDATE item SET stock = stock + qty FROM inserted WHERE item.id = deleted.id
end
I need help to create the same function of this query in MYSQL query
and i already do this
CREATE TRIGGER trigger1
BEFORE UPDATE ON buy_item
FOR EACH ROW
BEGIN
UPDATE item SET stock = stock - buy_item.qty WHERE item.id=buy_item.id
UPDATE item SET stock = stock + NEW.qty WHERE item.id=buy_item.id
END
but this isn't work at all, it says the syntax is wrong
maybe anyone can help about this
Thanks before
Assuming that you can't change item id in buy_item your trigger in MySql should look like this
CREATE TRIGGER trigger1
AFTER UPDATE ON buy_item
FOR EACH ROW
UPDATE item
SET stock = stock + NEW.qty - OLD.qty
WHERE id = NEW.id;
Here is SQLFiddle demo
A trigger body in mysql requires a number of SQL commands separated by a semi-colon (;). To create the full trigger code one must define its own delimiter to something else — such as $$.
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE UPDATE ON buy_item
FOR EACH ROW BEGIN
UPDATE item SET stock = stock - buy_item.qty WHERE item.id=buy_item.id;
UPDATE item SET stock = stock + NEW.qty WHERE item.id=buy_item.id;
END$$
This web site as helped me in the past for syntax and other relevant issues to mysql and triggers
http://www.sitepoint.com/how-to-create-mysql-triggers/
this is the error message after i write the syntax
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE UPDATE ON buy_item
FOR EACH ROW BEGIN
UPDATE item SET stock = stock - buy_item.qty WHERE item.id=buy_item.id;
UPDATE item SET stock = stock + NEW.qty WHERE item.id=buy_item.id;
END$$
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for right syntax to use near 'DELIMITER $$
CREATE TRIGGER Trigger1
BEFORE UPDATE ON buy_item
FOR EACH ROW' at line 1'"
My MySQL server version is 5.5.13

History field in MySQL database

Trying to create a field in a table that will get the old value of another field. My table is very similar to this:
------------ -------------------- ------------------------
| id int(10) | price decimal(5,2) | price_old decimal(5,2) |
----------------------------------------------------------
What I am trying to get is the value of price field to get copied in price_old field ON UPDATE of the current record.
Is it possible to achieve this only with mysql?
PS: The data contained in that cell is not critical. The usage is to store the previous price of a item and after to be able to show how it changed. I will only need the last value, not the full history of the table entry. (My MySQL server is 5.0, if this matters)
Yes, you can use a BEFORE UPDATE trigger (documentation).
I think this syntax is right but haven't used MySQL in a while so you may have to toy with it. If it's wrong and you get it working please let me know so I can edit it.
DELIMITER $$
CREATE TRIGGER `price_trigger`
BEFORE UPDATE ON `products`
FOR EACH ROW
BEGIN
IF NEW.price != OLD.price
SET price_old = OLD.price;
END IF;
END$$
DELIMITER ;
Use triggers on update rule. There set value of price to price_old
CREATE TRIGGER `update_price_old`
BEFORE UPDATE ON `table_name` FOR EACH ROW
BEGIN
UPDATE `table_name` SET price_old = OLD.price where OLD.id = id;
END

After insert trigger can do an update?

I'm new to the creation of triggers but I need it since I'm using a persistent storage for some IDs.
I have the table RECEIPT with a column RECEIPT_ID
and the table CONFIG_DB with columns and values:
NAME VALUE
--------------- -----
NEXT_RECEIPT_ID 1
and I created this trigger
CREATE TRIGGER UPDATE_RECEPCION_ID
AFTER INSERT ON RECEIPT
FOR EACH ROW
BEGIN
UPDATE CONFIG_DB SET VALUE=VALUE+1;
END
;
I don't know if this is OK... all I want its that after I insert a new RECEIPT_ID the VALUE in CONFIG_DB increases by 1. Thank you very much.
EDIT: I work in Mysql Workbench 5.2.40 with Mysql Server 5.5.25
Use following query to create trigger
delimiter |
CREATE
TRIGGER `UPDATE_RECEPCION_ID`
AFTER INSERT ON `RECEIPT`
FOR EACH ROW BEGIN
UPDATE CONFIG_DB SET VALUE=VALUE+1
WHERE NAME='NEXT_RECEIPT_ID';
END;
|