3

I have a table that contains the unit price and other details of each item in a store.

CREATE TABLE Item (Item_id CHAR(4), Description CHAR(40), Sizes CHAR(40), Weight REAL, Unit_price REAL, PRIMARY KEY(Item_id));

And another one that contains details of the items contained in each order.

CREATE TABLE Order_contains_items (Item_id CHAR(4), Order_no INT, Quantity_ordered INT, Ordered_price REAL, PRIMARY KEY(Item_id, Order_no), FOREIGN KEY(Order_no) REFERENCES Order(Order_no), FOREIGN KEY(Item_id) REFERENCES Item(Item_id));

Now I want to compute

Order_contains_items.Ordered_price = Item.Unit_price * Order_contains_items.Quantity_ordered WHERE Order_contains_items.Item_id = Item.Item_id

Note that I want it to be a part of the table itself and not as a different view or a query. How can I do this? I looked into triggers and other mechanisms for this but do they work for values in different tables especially with such constraints?

I tried the following trigger based on Column calculated from another column? :

CREATE TRIGGER Order_price BEFORE INSERT ON Order_contains_items
    FOR EACH ROW BEGIN
        SET NEW.Ordered_price = Item.Unit_price * NEW.Quantity_ordered
            WHERE NEW.Item_id = Item.Item_i
END;

But it didn't seem to work

Community
  • 1
  • 1
akhiljain
  • 621
  • 1
  • 9
  • 18
  • Yes, triggers can do it. You'll want to calculate a value on both `INSERT` and, if you allow it, `UPDATE`. – HABO Nov 23 '13 at 03:05
  • @HABO: I tried the following based on [link](http://stackoverflow.com/questions/5222044/column-calculated-from-another-column) `CREATE TRIGGER Order_price BEFORE INSERT ON Order_contains_items FOR EACH ROW BEGIN SET NEW.Ordered_price = Item.Unit_price * NEW.Quantity_ordered WHERE NEW.Item_id = Item.Item_i END;` But it didn't seem to work – akhiljain Nov 23 '13 at 03:19
  • Have you settled on mysql-server-2005, or are the two tables in different databases? – HABO Nov 23 '13 at 04:15
  • What RDBMS are you actually using SQL Server or MySQL? – peterm Nov 23 '13 at 05:56

1 Answers1

2

Here is how you can do that in MySQL (your question is tagged with both mysql and sql-server)

CREATE TRIGGER tg_bi_order_contains_items 
BEFORE INSERT ON Order_contains_items
FOR EACH ROW
  SET NEW.Ordered_price = 
  (
    SELECT Unit_price * NEW.Quantity_ordered
      FROM Item
     WHERE Item_id = NEW.Item_id
     LIMIT 1
  );

CREATE TRIGGER tg_bu_order_contains_items 
BEFORE UPDATE ON Order_contains_items
FOR EACH ROW
  SET NEW.Ordered_price = 
  (
    SELECT Unit_price * NEW.Quantity_ordered
      FROM Item
     WHERE Item_id = NEW.Item_id
     LIMIT 1
  );

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157