1

I get the following error: "Can't update table 'Product' in stored function/trigger because it is already used by statement which invoked this stored function/trigger."

CREATE TRIGGER `SalesDB`.`updateSum` AFTER UPDATE ON SalesDB.Product FOR EACH ROW
BEGIN
  DECLARE totalStock INT;

  SELECT SUM(stock) 
      INTO totalStock
      FROM Product
      WHERE Product.prodID= NEW.prodID;

  UPDATE Product SET StockSum = totalStock
      WHERE  prodID = NEW.prodID;
END;

I understand that there is a recursive issue, but how do I do something like this? Is there a way to use triggers to do this kind of thing? Should this be done in a Stored Procedure instead, and how do I run the stroed procedure on a Update Product event?

I need to update the stock of a product and then go thru all rows that have the same prodID calculate the SUM and Update the SumTotal field of all the rows.

4

1 回答 1

1

UPDATED Unfortunately you can't do this in MySql due to the limitations of triggers implementation.

Possible options are:

  1. Create stored procedure and call it after each update on Product table
  2. Store stockSum in a separate table (e.g. ProductStock), use triggers (INSERT, UPDATE) to update stockSum values, create a view on joined Product and ProductStock
  3. Use MySql events or a cron job to update stockSum in Product table if some delay is acceptable

IMHO best approach is 2 separating Product and ProductStock tables:

ProductStock might look like this

CREATE TABLE ProductStock
(
  prodID int NOT NULL PRIMARY KEY,
  stockSum decimal(12, 3)
);

Now triggers

CREATE TRIGGER tg_product_update
AFTER UPDATE ON Product 
FOR EACH ROW
CALL sp_updateProductStock(NEW.prodID);

CREATE TRIGGER tg_product_insert
AFTER INSERT ON Product 
FOR EACH ROW
CALL sp_updateProductStock(NEW.prodID);

and a stored procedure

CREATE PROCEDURE sp_updateProductStock(IN ProductID INT)
REPLACE INTO ProductStock (prodID, stockSum) 
SELECT ProductID, 
       (SELECT SUM(COALESCE(stock, 0)) 
          FROM Product
         WHERE prodID = ProductID);

And finally a view

CREATE VIEW vw_Product AS
SELECT p.id, p.prodID, ... , p.stock, s.stockSum
  FROM Product p JOIN ProductStock s
    ON p.prodID = s.prodID

Here is SQLFiddle example

于 2013-05-22T17:52:53.183 回答