Reputation: 97
I have two tables -
part(partID, brand, price, size)
consists_of(customerID, partID, quantity, price, shipdate)
|
FK part.ID from part
Table part
is never going to be changed/updated, but consists_of
will be.
- How do I add a [before insert?] trigger on
consists_of
that checks ifconsists_of.price
for each entry is less than or equalconsists_of.quantity * part.price
for that particularconsists_of.partID
and raises an abort if it isn't so?
Or,
- How do I add [after insert?] trigger on
consists_of
that doesINSERT INTO consists_of(price) VALUES (...)
where the value ofconsists_of.price
is equal toconsists_of.quantity * part.price
for thatconsists_of.partID
?
Upvotes: 0
Views: 1388
Reputation: 400
If I understand you correctly, you can select part.price
in subqueries and calculate part.price * consists_of.quantitiy
.
CREATE TABLE part(part_id INTEGER, price INTEGER);
CREATE TABLE consists_of(customer_id INTEGER, part_id INTEGER, quantity INTEGER, price INTEGER);
INSERT INTO part VALUES(10, 50);
INSERT INTO part VALUES (20, 1000);
CREATE TRIGGER IF NOT EXISTS raise_if_consists_of_price_too_expensive
AFTER INSERT ON consists_of
WHEN new.price > (SELECT part.price * new.quantity FROM part WHERE part.part_id = new.part_id)
BEGIN
SELECT RAISE (ABORT, 'too expensive.');
END;
-- OK
INSERT INTO consists_of(customer_id, part_id, quantity, price)
VALUES(10050, 20, 31, 100);
-- OK
INSERT INTO consists_of(customer_id, part_id, quantity, price)
VALUES(80030, 10, 9, 50 * 9);
-- Raise abort
INSERT INTO consists_of(customer_id, part_id, quantity, price)
VALUES(80099, 10, 9, 50 * 9 + 1);
CREATE TABLE part(part_id INTEGER, price INTEGER);
CREATE TABLE consists_of(customer_id INTEGER, part_id INTEGER, quantity INTEGER, price INTEGER);
INSERT INTO part VALUES(10, 50);
INSERT INTO part VALUES (20, 1000);
CREATE TRIGGER IF NOT EXISTS fill_consists_of_price
AFTER INSERT ON consists_of
BEGIN
UPDATE consists_of
SET
price = (
SELECT consists_of.quantity * part.price
FROM part
WHERE part.part_id = consists_of.part_id
)
WHERE customer_id = new.customer_id AND part_id = new.part_id
;
END;
INSERT INTO consists_of(customer_id, part_id ,quantity)
VALUES(10050, 20, 31);
INSERT INTO consists_of(customer_id, part_id ,quantity)
VALUES(80033, 10, 9);
Upvotes: 1