How to write a 'Before Delete' trigger in SQL - mysql

I am currently working on a homework project where we are creating triggers user plpgsql
I've managed to figure out the trigger for update/insert but I'm having trouble with writing
a delete one and feel like im going round in circles with the online documentation.
The two tables we're given are:
MAJOR(mCode, name) with primary key mCode.
STUDENT(sId, firstName, lastName, mCode, pointsEarned) with primary key {sId} and foreign key mCode
The requirement is basically that a major cannot be deleted or changed if a student has chosen the major.
(I've already implemented the update/insert trigger)
I'm 99% sure my create trigger will just be:
CREATE TRIGGER major_delete
BEFORE UPDATE OR INSERT ON student
FOR EACH ROW EXECUTE PROCEDURE major_delete_trigger();
And I have come up with two basic ideas for the function (based off lectures notes):
CREATE OR REPLACE FUNCTION major_delete_trigger()
RETURNS trigger AS $$
DECLARE m RECORD;
BEGIN
SELECT * INTO m FROM major WHERE OLD.mcode = mcode;
IF NOT FOUND THEN RETURN OLD;
ELSE
DELETE FROM major WHERE mcode = OLD.mcode;
RETURN NULL;
END IF;
END;
$$ LANGUAGE 'plpgsql';
Which does nothing at all - when running a test on my database deletes that should be failing still succeed.
Secondly:
CREATE OR REPLACE FUNCTION major_delete_trigger()
RETURNS trigger AS $$
BEGIN
IF (TG_OP = 'DELETE') THEN
DELETE FROM major WHERE mcode=OLD.mcode;
IF NOT FOUND THEN RETURN NULL; END IF;
END IF;
END;
$$ LANGUAGE 'plpgsql';
Which executes the line 'DELETE FROM major WHERE mcode = OLD.mcode;' until there is no room left on the stack.
When doing my update function I found I was just looking at it as if it was really complicated so I'm not sure if this will be the same.
Any ideas or documentation that could help will be much appreciated!

Related

stored procedure returning `ASCII \0` error but can't find what that is referring to

I am writing my first stored procedure as a trigger. I am doing this in a dev migration as we have two systems which don't speak to each other in dev, so I need to mock the data which would normally come from the other system.
My procedure is added as part of our dev migration script.
DELIMITER |;
CREATE TRIGGER `activity_insert` AFTER INSERT ON `activity`
FOR EACH ROW
BEGIN
UPDATE `activity` AS `a` JOIN `handle` AS `h` on `a.handle_id` = `h.handle_id` SET `path` = CONCAT(`h.handle`,'/',`a.activity_handle`) WHERE `a.path` IS NULL;
END;
|
DELIMITER;
I would expect the logic to be:
DELIMITER $$
CREATE TRIGGER activity_insert BEFORE INSERT ON activity
FOR EACH ROW
BEGIN
IF new.path IS NULL THEN
SET new.path = (SELECT CONCAT(h.handle, '/', new.activity_handle)
FROM handle h
WHERE new.handle_id = h.handle_id
);
END IF;
END;$$
DELIMITER;
There are numerous problem with your code:
You don't update the table being modified using update.
You want a "before" triggers, not an "after trigger".
Don't use | for the the delimited. It is a valid MySQL operator.
You have over-used the backtick, including putting the table alias in with the column alias.
This assumes that handle.handle_id is unique. This seems like a reasonable assumption based on the names, but you can add limit 1 to guarantee no more than one row is returned.

MySQL TRIGGER to INSERT BEFORE INSERT using SELECT, IF, etc

I am trying to write a trigger that combines an insert & select, I've found numerous topics online, but, none seem to relate to my exact problem, maybe I am missing something with my structure?
The aim of this is that on the event of a cancellation in our audit log, then I define a cancellation reason based on a series of business logic in another table, this logic is drawn together in a SELECT using CASE & subqueries.
I want to expand the following trigger that currently works and replace the SET cancellation_point='test' element with the SELECT query I just mentioned.
DELIMITER $$
CREATE
TRIGGER `cancellation_stage` BEFORE INSERT ON `log`
FOR EACH ROW
BEGIN
IF (NEW.status='cancel' AND NEW.type='0') THEN
INSERT INTO cancellation_stage
SET
id=NEW.id,
property_id=NEW.entity_id,
cancellation_date=NOW(),
cancellation_point='test';
END IF;
END;
$$
DELIMITER ;
I did try to construct this myself using various guidance from here, but, its just not working. I got this code to physically save as a trigger, but, it did not populate the data in the database (I have replaced my SELECT with a basic query example below):
DELIMITER $$
CREATE
TRIGGER `cancellation_stage` BEFORE INSERT ON `log`
FOR EACH ROW
BEGIN
DECLARE cancellation_point VARCHAR(255);
SET cancellation_point = ( SELECT * FROM x);
IF (NEW.transition='cancel' AND NEW.entity_type='property') THEN
INSERT INTO cancellation_stage
SET
id=NEW.id,
property_id=NEW.entity_id,
cancellation_date=NOW(),
cancellation_point=NEW.cancellation_point;
END IF;
END;
$$
DELIMITER ;
Any help would be greatly appreciated :)

MySQL create trigger declare

I am trying to complete this question
**
Produce an audit trail (in a separate table) that records the current username, system date & grade change when someone attempts to update a Students grade
**
Here are the tables and columns
Module (code,credits,cost,name)
session (code,date,room)
Exam (no,code,grade)
course (code,credits,name)
Student (no,name,cell)
Here is the code I have so far
DELIMITER $$
USE `HarlemHS`$$
CREATE
DEFINER=`HarlemHS`#`%`
TRIGGER `HarlemHS`.`ExamChange`
AFTER UPDATE ON `HarlemHS`.`Exam`
FOR EACH ROW
BEGIN
INSERT INTO NEW.GradeUpdateLog Date_Of_Change,old_grade)
VALUES (CURDATE(), grade);
END$$
I know I have to use DECLARE somewhere but not too sure where to use it and what to put in the DECLARE statement.
If i have missed anything let me know,
Thank you for the help :)

MySQL write a trigger to prevent from buying too much

I have a table warehouse where I have information about articles in my store (article id as foreign key and quantity). Then, I have another table, shoppinglist where I have a clients id, article id and quantity. Lets say, that client wants to buy 3 articles but theres only one article available. How to write a trigger which help me to prevent from buying too much?
I tried this:
DELIMITER $$ CREATE TRIGGER check BEFORE INSERT ON shoppinglist FOR EACH ROW BEGIN IF warehouse.quantity < shoppinglist.quantity THEN CALL fail('You cant buy that much'); END IF; END $$ DELIMITER;
but this seems not to work. I mean, when I do:
INSERT INTO shoppinlist (clients_id, article_id, quantity) VALUES (1, 2, 100);
having only 2 articles with id = 2 on warehouse its ok, its possible. What did I do wrong?
What specific article would warehouse.quantity or shoppingList.quantity refer to in your code?
Also, check is a reserved keyword.
Try this:
DELIMITER $$
CREATE TRIGGER qtyCheck BEFORE INSERT ON shoppinglist
FOR EACH ROW
BEGIN
SET #qty = (SELECT quantity FROM warehouse WHERE article_id = NEW.article_id);
IF #qty < NEW.quantity THEN
CALL fail('You cant buy that much');
END IF;
END $$
DELIMITER ;
Note that I renamed the trigger, I'm guessing the name of the article_id column on the warehouse table, I used the NEW variable instead of shoppingList within the body of the trigger, and you need a space before the semicolon in DELIMITER ;, though this might've been a typo when posting.
Finally, you may get the following error if the fail function isn't defined. It doesn't exist on my system...
ERROR 1305: PROCEDURE testing.fail does not exist

MySQL Trigger to update another table

I have the following two tables in a MySql database:
Bookings
BookingID | ClientID | SeatID
SeatAvailability
SeatAvailabilityID | BookingID | ShowID | Available
They are linked on SeatID/SeatAvailabilityID.
I'm trying to write a trigger which updates the SeatAvailability table each time a row is inserted in Bookings. The trigger should change SeatAvailability.Available to 0 and also enter the BookingID from Bookings into the BookingID field in SeatAvailability with the same SeatAvailabilityID.
I've written this trigger, MySql accepts it but gives an error when inserting
"ERROR 1054: Unknown column 'cinemax.bookings.SeatID' in 'where clause'".
DELIMITER $$
USE `cinemax`$$
CREATE
DEFINER=`root`#`localhost`
TRIGGER `cinemax`.`update_available`
AFTER INSERT ON `cinemax`.`bookings`
FOR EACH ROW
UPDATE cinemax.seatavailability
SET cinemax.seatavailability.Availabe=0, cinemax.seatavailability.BookingID=cinemax.bookings.BookingID
WHERE cinemax.bookings.SeatID=cinemax.seatavailability.SeatAvailabilityID$$
try
AFTER INSERT ON `cinemax`.`bookings`
instead of
AFTER UPDATE ON `cinemax`.`bookings`
It's a couple of months late, but I decided to give it a quick shot before handing in the overall assignment. In the meantime I switched to postgres as it seemed to offer more functionality (albeit not as user friendly). I first had to create a trigger function:
CREATE OR REPLACE FUNCTION updateseatavailable()
RETURNS trigger AS
$BODY$
BEGIN
IF (TG_OP = 'INSERT') THEN
UPDATE "SeatAvailability"
SET "Available"='FALSE' AND "BookingID"=NEW."BookingID" WHERE "SeatAvailabilityID"=NEW."SeatID";
ELSIF (TG_OP = 'DELETE') THEN
UPDATE "SeatAvailability"
SET "Available"='TRUE' WHERE "SeatAvailabilityID"=OLD."SeatID";
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
and then simply call the function/procedure from a trigger:
CREATE TRIGGER UpdateSeatAvailable
AFTER INSERT OR DELETE ON "Bookings"
FOR EACH ROW
EXECUTE PROCEDURE updateSeatAvailable();
I wasn't able to get the BookingID in SeatAvailability to update for some reason (on Insert nothing happened and on Delete I got an error telling me Available cannot be null, even though I was changing the BookingID) so I omitted that in postgres,and implemented it with Java instead. It's not the best way but still better than nothing.
I decided to post my solution just in case someone has a similar problem and stumbles upon this question.