SQL Trigger update on same table - mysql

I want to create a trigger in MySQL for the following table such that if the attribute of occurrences is greater than 100 the attribute of status updates to "popular".
The name of the table is trigger
Repo_ID |Occurences |Status
1 | 50 | Normal
2 | 70 | Normal
3 | 190 | Popular
I've tried the following thing. It didnt work. Any suggestions?
CREATE TRIGGER `A` after update
ON `trigger`
FOR EACH ROW BEGIN
IF (new.occurence > 100) THEN
SET new.STATUS = "popular";
ELSE SET new.STATUS = "normal";
END IF;
END

You want a before update trigger:
CREATE TRIGGER `A` before update ON `trigger`
FOR EACH ROW
BEGIN
SET new.STATUS = (CASE WHEN new.occurences > 100 THEN 'popular' ELSE 'normal' END);
END;
I also removed the IF because CASE seems more concise.

Related

Trigger to update a counter when data is entered in another table's column

Let's say I have a table named Count and a table named Records.
Count table:-
| countRecords | typeRecord |
|--------------|--------------------|
| 0 | type of record |
Records table:-
| ID | recordType |
|------------|------------------|
| id | type of record |
I want to update the countRecords as per the type in recordType in table Records. Whenever a user enters a recordType, I want to update the counter for it in Count table and whenever a user deletes a row/entry, I want to decrement the counter. How do I do this using a trigger?
Basically you need two triger
The insert trigger, as long as it only needs to update a row, can be done so.
If your database is more complex and you have fpor example an empty recordType , you need more code
CREATE TRIGGER after_recods_insert
AFTERINSERT
ON recods FOR EACH ROW
UPDATE count_table SET countRecords = countRecords +1 WHERE typeRecord = NEW.recordType ;
AN UPDATE Trigger ist somewhat more complex as you need to change teh count when the type changes
DELIMITER $$
CREATE TRIGGER after_recods_UPDATE
AFTER UPDATE
ON recods FOR EACH ROW
BEGIN
IF (OLD.recordType <> NEW.recordType) THEN
UPDATE count_table SET countRecords = countRecords -1 WHERE typeRecord = OLD.recordType ;
UPDATE count_table SET countRecords = countRecords +1 WHERE typeRecord = NEW.recordType ;
END IF;
END$$
DELIMITER ;
Serg is right, to complte the set
CREATE TRIGGER after_recods_delete
AFTER DELETE
ON recods FOR EACH ROW
UPDATE count_table SET countRecords = countRecords - 1 WHERE typeRecord = OLD.recordType ;

How to make triggers for delete and adding with if statement MySQL?

have two table's Queue (appointment_id, actual_time) Queue_Summary (date, doctor_id, num_of_patients)
The first is all the queues there are and the second is how many queues for each doctor on a certain date. I need to build a trigger that updates the num_of_patients, every time in Queue that a queue is added I need to add to a doctor num_of_patients on that date. Also when removing.
I have just counted the number of queues given a doctor_id and date, made it into two triggers.
But the only problem I have is where do I place the if statement that checks if this date is on Queue_Summary and if not adds it.
(P.S - Im not 100% on thoes also as my database is a bit off and does tons of problems, if there are any problem in thoes statments I'll be more them happy to know)
delimiter //
CREATE TRIGGER update_queue_summary
AFTER DELETE ON queue
FOR EACH ROW
BEGIN
update queue_summary as qs set num_of_patient = (
select count(appointment_id)
from queue as q join appointment as a on appointment_id
where a.doctor_id=qs.doctor_id and date(qs.actual_time)=date(qs.date())
group by appointment_id
) where doctor_id=qs.doctor_id and date(qs.actual_time)=date(qs.date());
END;//
delimiter ;
delimiter //
CREATE TRIGGER update_queue_summary
AFTER insert ON queue
FOR EACH ROW
BEGIN
update queue_summary as qs set num_of_patient = (
select count(appointment_id)
from queue as q join appointment as a on appointment_id
where a.doctor_id=qs.doctor_id and date(qs.actual_time)=date(qs.date())
group by appointment_id
) where doctor_id=qs.doctor_id and date(qs.actual_time)=date(qs.date());
END;//
delimiter ;
You should carry out an existence test in your trigger. For example
drop table if exists queue,queue_summary;
create table queue (appointment_id int auto_increment primary key, doctor_id int,actual_time datetime);
create table Queue_Summary (date date, doctor_id int, num_of_patients int);
delimiter $$
create trigger ut after insert on queue
for each row
begin
if not exists (select 1 from queue_summary where date = date(new.actual_time) and doctor_id = new.doctor_id) then
insert into queue_summary values(date(new.actual_time),new.doctor_id,1);
else
update queue_summary
set num_of_patients = num_of_patients + 1
where date = date(new.actual_time) and doctor_id = new.doctor_id;
end if;
end $$
delimiter ;
insert into queue (doctor_id,actual_time) values(1,'2020-05-03 09:00'),(1,'2020-05-03 09:30');
select * from queue;
select * from queue_summary;
MariaDB [sandbox]> select * from queue;
+----------------+-----------+---------------------+
| appointment_id | doctor_id | actual_time |
+----------------+-----------+---------------------+
| 1 | 1 | 2020-05-03 09:00:00 |
| 2 | 1 | 2020-05-03 09:30:00 |
+----------------+-----------+---------------------+
2 rows in set (0.001 sec)
MariaDB [sandbox]> select * from queue_summary;
+------------+-----------+-----------------+
| date | doctor_id | num_of_patients |
+------------+-----------+-----------------+
| 2020-05-03 | 1 | 2 |
+------------+-----------+-----------------+
1 row in set (0.001 sec)
And a delete trigger is similar but simpler
delimiter $$
create trigger dt after delete on queue
for each row
begin
if exists (select 1 from queue_summary where date = date(OLD.actual_time) and doctor_id = old.doctor_id) then
update queue_summary
set num_of_patients = num_of_patients - 1
where date = date(old.actual_time) and doctor_id = old.doctor_id;
end if;
end $$
delimiter ;
The existence check is entirely cosmetic since a delete won't complain if there is nothing to delete.

Trigger "AFTER INSERT" doesn't work, after insertion if I Add values in tables?

Purpose of trigger:
I should +add some number 50 to that user to table money where in table paym both columns table1 and table2 are not empty.
For example: User 'John' has both columns not empty and to him added 50 in table money.
Example in table below:
table: paym
ID username table1 Table2
+-------+-------------+-------------+-----------+
| 1 | John | Value | Value |
+-------+-------------+-------------+-----------+
| 2 | Alex | Null | Null |
+-------+-------------+-------------+-----------+
Table: money
ID username total_money
+-------+-------------+-------------+
| 1 | John | 50 |
+-------+-------------+-------------+
| 2 | Alex | 0 |
+-------+-------------+-------------+
Trigger below, works perfectly only when we insert all tables at one time. But it doesn't work if you insert only username two tables empty and after insertion, if you add values to empty tables table1 and table2 triggers not works at this point! Can we solve this problem???
Trigger should work even if we add value to the table After insertion!
DELIMITER $$
CREATE trigger update_money_after_paym
AFTER INSERT ON paym
FOR EACH ROW
BEGIN
IF (NEW.table1 IS NOT NULL AND NEW.table2 IS NOT NULL) THEN
UPDATE money SET total_money = total_money + 50 WHERE username = NEW.username;
END IF;
END;
$$
DELIMITER;
Not that trigger. It is an insert trigger, so it doesn't get called for an update.
If you want an update trigger, then define one:
DELIMITER $$
CREATE trigger update_money_after_paym
AFTER UPDATE ON paym
FOR EACH ROW
BEGIN
IF (NEW.table1 IS NOT NULL AND NEW.table2 IS NOT NULL) THEN
UPDATE money m
SET total_money = total_money + 50
WHERE m.username = NEW.username;
END IF;
END;
$$
DELIMITER;
This may not do exactly what you want. For instance, you might only want to add 50 when the previous values are both NULL:
DELIMITER $$
CREATE trigger update_money_after_paym
AFTER UPDATE ON paym
FOR EACH ROW
BEGIN
IF (NEW.table1 IS NOT NULL AND NEW.table2 IS NOT NULL AND
OLD.table1 IS NULL AND old.table2 IS NULL) THEN
UPDATE money m
SET total_money = total_money + 50
WHERE m.username = NEW.username;
END IF;
END;
$$
DELIMITER;

Mysql trigger when on update reserved cloumn sub capacity if statements

I want to set check class capacity if will be full class should be
confirm. When I update reserved it give error. Please help. Thank you.
CREATE TRIGGER `control_class_capacity`
AFTER UPDATE ON `learningcenter_class`
FOR EACH ROW BEGIN
IF NEW.capacity - NEW.reserved = 0 THEN BEGIN
UPDATE learningcenter_class SET isconfirm = 1 WHERE class_id = NEW.class_id;
END; END IF;
END
Assuming your class_id is unique you could change the trigger to a before trigger and set NEW.ISCONFIRM. BTW if statements in MYSQL do not require begin and end statements.
drop table if exists t;
create table t(class_id int ,capacity int, reserved int, isconfirm int);
insert into t values (1,1,0,0) , (2,1,0,0);
drop trigger if exists `control_class_capacity`;
delimiter $$
CREATE TRIGGER `control_class_capacity`
before UPDATE ON t
FOR EACH ROW BEGIN
IF NEW.capacity - NEW.reserved = 0 THEN
SET new.isconfirm = 1;
END IF;
END $$
delimiter ;
update t set reserved = 1 where class_id = 1;
select * from t;
+----------+----------+----------+-----------+
| class_id | capacity | reserved | isconfirm |
+----------+----------+----------+-----------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 0 | 0 |
+----------+----------+----------+-----------+
2 rows in set (0.00 sec)

generated column with condition sql

mysql command to generate a column from other column according to condition
loan_amount | installment | start_date | status
------------------------------------------------------------------
500 | 100 | 2018-1-1 |
if (loan_amount % installment != 0) then month_required to pay = loan_amount / installment + 1
else month_required = loan_amount / installment;
then i want to check by adding month_required to start_date if it has crossed current date. If not then status would generate "incomplete" else "complete" .
delimiter //
set #month = "0";
create trigger `status_check` before insert on `loan`
for each row
begin
if NEW.loan_amount% NEW.installment != 0
then set #month NEW.loan_amount/ NEW.installment +1;
else set #month = NEW.loan_amount/NEW.installment;
end if ;
if NOW() <= dateadd(NEW.start_date,INTERVAL #month MONTH)
then set NEW.status = "incomplete";
else set NEW.status = "complete";
end if;
end;
//
DELIMITER ;
what is the error here? please help.
I Can't make the real answer as you don't provide all your database field nor a data sample, but some BEFORE INSERT and BEFORE UPDATE Trigger will probably do the job.
This is the base for the BEFORE INSERT :
DELIMITER //
DROP TRIGGER IF EXISTS `trg_test_insert`;
//
CREATE TRIGGER `trg_test_insert`
BEFORE INSERT ON `table`
FOR EACH ROW
BEGIN
IF NEW.loan_amount % NEW.installment != 0 THEN
SET NEW.month_required = NEW.loan_amount / NEW.installment + 1;
ELSE
SET NEW.month_required = NEW.loan_amount / NEW.installment;
END IF;
END;
//
DELIMITER ;
Take a look at MySQL 5.7 Reference Manual / ... / Trigger Syntax and Examples
And at :
MYSQL Triggers - how to store the result of a calculated field