0

I have two tables, tbl_stock and tbl_stockEntry, those two tables are identical.

They have these fields: warehouse cultivar variety quantity

when an entry is entered in to the tbl_stockEntry table I would like it to either update the matching entry in the tbl_stock table or create a new entry if there is no matching entry.

But I need it to match 3 fields, warehouse, cultivar and variety.

This is my trigger to create the entry, but I can't seem to get it to insert a record if none is found.

BEGIN
  UPDATE tbl_stock
     SET quantity = quantity + NEW.quantity
   WHERE vegetableCultivar = NEW.vegetableCultivar
   AND warehouse = NEW.warehouse;
END

I have tried this and but it doesnt work:

BEGIN
  UPDATE tbl_stock
     SET quantity = quantity + NEW.quantity
   WHERE vegetableCultivar = NEW.vegetableCultivar
   AND warehouse = NEW.warehouse;
     if sql%rowcount = 0 then  
    -- nothing was updated, so the record doesn't exist, insert it. 
    insert into tbl_stock (warehouse, vegetableCultivar, vegetableVariety, quantity)
            values (NEW.warehouse, NEW.vegetableCultivar, NEW.vegetableVariety, NEW.quantity);
  end if;
END

If anyone knows how I could accomplish this I would really appreciate some assistance.

1
  • The reason I need all 3 matched is that there should be multiple warehouses, each with the same item, so warehouse 1 and warehouse 1 could both have the same cultivar and variety, so if i only match one or two of the fields I will have the wrong entries being updated. Commented Oct 1, 2018 at 1:25

1 Answer 1

1

Ok this is working:

BEGIN
  UPDATE tbl_stock
     SET quantity = quantity + NEW.quantity
   WHERE vegetableCultivar = NEW.vegetableCultivar
   AND warehouse = NEW.warehouse;

    IF ROW_COUNT() = 0 THEN  
    INSERT INTO tbl_stock (warehouse, vegetableCultivar, vegetableVariety, quantity)
  values (NEW.warehouse, NEW.vegetableCultivar, NEW.vegetableVariety, NEW.quantity);
  end if;
END
Sign up to request clarification or add additional context in comments.

Comments

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.