4

I have 2 tables:

Books - isbn (PK), title, qty-in-stock
Orderlist - ordernum (PK), isbn, quantity

My goal is to insert a record into orderlist and then, if matching isbns, add the quantity to qty-in-stock

My function and trigger is not correct -

CREATE OR REPLACE FUNCTION books_upd() RETURNS trigger as $bookupd$
BEGIN 
--IF   THE ISBN MATCHES BETWEEN BOOKS AND ORDERLIST
-- ADD THE EXISTING QTY_IN_STOCK (BOOKS)  TO QUANTITY (ORDERLIST)
QTY_IN_STOCK:=QTY_IN_STOCK+QUANTITY;
--END IF
RETURN NEW;
$bookupd$ LANGUAGE plpgsql;

CREATE TRIGGER books_upd
BEFORE INSERT OR UPDATE on orderlist
FOR EACH ROW
EXECUTE PROCEDURE books_upd();

Can anyone help?

1 Answer 1

1

The trigger function is quite complicated because of different cases of insert and update.

When a user updates the order, then the function should:

  • add to qty_in_stock the difference between new and old quantities if isbns are the same or
  • subtract old quantity from qty_in_stock of one book and add new quantity to qty_in_stock of another book when isbns are different.

Additionally, the function should reject changes if the given isbn does not exist in books.

CREATE OR REPLACE FUNCTION books_upd() 
RETURNS trigger as $bookupd$
DECLARE
    v_quantity int;
BEGIN
    v_quantity = NEW.quantity;
    IF TG_OP = 'UPDATE' THEN
        IF OLD.isbn != NEW.isbn THEN
            UPDATE books
            SET qty_in_stock = qty_in_stock- OLD.quantity
            WHERE isbn = OLD.isbn;
        ELSE
            v_quantity = NEW.quantity- OLD.quantity;
        END IF;
    END IF;

    UPDATE books
    SET qty_in_stock = qty_in_stock+ v_quantity
    WHERE isbn = NEW.isbn;

    IF NOT FOUND THEN
        RAISE EXCEPTION 'Uknown isbn';
    END IF;
    RETURN NEW;
END;
$bookupd$ LANGUAGE plpgsql;

Read more about NEW, OLD and TG_OP.


The trigger function only for insert is really simple:

CREATE OR REPLACE FUNCTION books_upd() 
RETURNS trigger as $bookupd$
BEGIN
    UPDATE books
    SET qty_in_stock = qty_in_stock+ NEW.quantity
    WHERE isbn = NEW.isbn;

    RETURN NEW;
END;
$bookupd$ LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

2 Comments

Actually, I made this too complicated. Sorry! We would only have an insert case. Also, isbn from orderlist is foreign key to isbn in books. So, it will always be found. I don't believe we need your second bullet point. Your answer was very helpful! Given these simplifiers, what is a new coding?
An additional challenge as business rules are developed- I found out that SET qty_in_stock = qty_in_stock+ NEW.quantity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.