Question

delimiter //
CREATE TRIGGER Discount
BEFORE INSERT ON ORDER_TABLE
FOR EACH ROW BEGIN
    DECLARE OrderNum INT;
    DECLARE Membership BOOLEAN;
    DECLARE Disc DECIMAL(10, 2);
    DECLARE Cost DECIMAL(10, 2);

    SELECT OrderCount INTO OrderNum
    FROM Customer
    WHERE CustomerID = NEW.CustomerID;

    SELECT Member INTO Membership
    FROM Customer
    WHERE CustomerID = NEW.CustomerID;

    SELECT Discount INTO Disc
    FROM Order_Table
    WHERE OrderID = NEW.OrderID;

    SELECT Price INTO Cost
    FROM Order_Table
    WHERE OrderID = NEW.OrderID;

    IF(Membership = TRUE) THEN
        IF(MOD(OrderCount, 10) = 0) THEN
            SET NEW.Discount = Cost/2;
        END IF;
    END IF;
END//
delimiter;

Above is a trigger for the database I am writing for a dry cleaning store. The trigger is supposed to make it so that every customer that has a membership at the dry cleaning store receives a discount with every 10th order they make. However when we enter the following data

insert into order_table values(0, 1, curdate(),20140426, null , 100, 10, 0, 110);

We get error 1054: Unknown column OrderCount in field list even though OrderCount exists in the customer table

Was it helpful?

Solution

First of all, the error message is coming from using OrderCount in the if block. You should be using the variable you declared and read this value into, OrderNum.

The other problem you might have, which I can't tell from this design, is when the Order Number is being updated. It might be best to add this to the trigger, so that the count of orders in the Customer tables is increased by one with the trigger, which can then be checked.

I just added this line to the trigger (after the variable declarations):

UPDATE `customer` SET `OrderCount`=OrderCount+1 WHERE `CustomerID`=NEW.CustomerID; 

OTHER TIPS

I work with oracle and it's quite different, but reading your trigger i suggest you , to rewrite the 4 querys to 2, this way you can avoid read each table twice.

.: .:

.:
 SELECT OrderCount, Member 
    INTO OrderNum, Membership
    FROM Customer
    WHERE CustomerID = NEW.CustomerID;

    SELECT Discount, Price 
    INTO Disc, Cost
    FROM Order_Table
    WHERE OrderID = NEW.OrderID;

.: .: .:

There's a bug in MySQL 5.6.17 on triggers when you reference another table that has been truncated: http://bugs.mysql.com/bug.php?id=72446

Maybe that's the reason? I'm trying to work around this by changing my TRUNCATE table_name to DELETE FROM table_name. (Also, the bug report seems to indicate that this is fixed in MySQL 5.6.19, but I haven't tested this yet.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top