How to automatically update table when values are added in SQL - mysql

I have a table:
vacation_days:
id name work_days hire
-------------------------------------
1 John 369 20151226
2 Mike 767 20141123
3 Josh 1166 20131020
There is a formula to get hire:
UPDATE vacation_days SET work_days = DATEDIFF(CURDATE(),DATE(hire))
However if I add a new row I get null values:
id name work_days hire
-------------------------------------
1 John 369 20151226
2 Mike 767 20141123
3 Josh 1166 20131020
4 Richard NULL 20120623
I have tried to use a trigger like so:
CREATE TRIGGER onInsert BEFORE INSERT ON vacation_days
FOR EACH ROW
BEGIN
SET NEW.work_days = DATEDIFF(CURDATE(),DATE(hire))
END;
However I get an error:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
''vacation_days' FOR EACH ROW SET work_days = DATEDIFF(CURDATE(), DATE
(NEW.hire))' at line 1

Don't update! Just use a view:
create view v_vacation_days
select vd.*, DATEDIFF(CURDATE(), DATE(vd.hire)) as workdays
from vacation_days vd;
Then the value will be up-to-date whenever you query the view.
Note: You need to remove workdays from the table definition.

Here you are using Insert Before, But the Hire data is not available until inserted, so you can not get the Hire date for the calculations. You want to indicate NEW or OLD Hire data for the usage.
Use this following Insert Before Trigger for your usage,
DELIMITER //
CREATE TRIGGER vacation_days_before_insert
BEFORE INSERT
ON vacation_days FOR EACH ROW
BEGIN
-- Insert record into table
INSERT INTO vacation_days
( id,
name,
work_days,
hire)
VALUES
( NEW.id,
NEW.name,
DATEDIFF(CURDATE(),DATE(NEW.hire)),
NEW.hire );
END; //
DELIMITER ;

Related

MYSQL: Using a trigger to make a unix timestamp on INSERT but allow for cloning existing records and avoiding duplicates

I am making an events system.
Let's say an event is "Go dancing" September 12th 2022.
When an event is added to the database we make a unix timestamp on one of the rows.
We use default value unix_timestamp() to do this
This timestamp say 654213987 is used as part of the url so people can sign up to event 654213987.
People can sign up here for example.
http://myevents/signup/654213987
The event organiser writes a description of the event on September 12 2022.
Next year the event organiser wants to do the same event but does not want to rewrite the descriptions. Just duplicate or clone the original without deleting the original.
This would be easy to do programmatically with PHP but I am using XCRUD which I can't modify so my only option is to use triggers or some hard wired part of MYSQL.
When XCRUD makes the duplicate it uses a normal INSERT with a copy of the original minus the primary.
If I make the column UNIQUE it does not allow the clone.
If not it makes a duplicate of the timestamp.
Is it possible to make a trigger (or some other mechanism) which would recognise that there is a duplicate and replace the duplicate with another fresh timestamp?
I have seen on stackoverflow that it is possible to add timestamps with triggers but I just can't figure out how to do this to avoid duplicates.
A sample.
CREATE TABLE test (id INT, ts DATE);
CREATE TRIGGER tr_bi_test_add_1_week
BEFORE INSERT ON test
FOR EACH ROW
BEGIN
WHILE EXISTS ( SELECT NULL
FROM test
WHERE ts = NEW.ts ) DO
SET NEW.ts = NEW.ts + INTERVAL 1 WEEK;
END WHILE;
END
INSERT INTO test VALUES (1, '2022-01-01');
-- inserted as-is
SELECT * FROM test;
id
ts
1
2022-01-01
INSERT INTO test VALUES (2, '2022-01-02');
-- inserted as-is
INSERT INTO test VALUES (3, '2022-01-15');
-- inserted as-is
SELECT * FROM test;
id
ts
1
2022-01-01
2
2022-01-02
3
2022-01-15
INSERT INTO test VALUES (4, '2022-01-01');
-- 2022-01-01 is present => 2022-01-08
SELECT * FROM test;
id
ts
1
2022-01-01
2
2022-01-02
3
2022-01-15
4
2022-01-08
INSERT INTO test VALUES (5, '2022-01-01');
-- 2022-01-01, -08, -15 is present => 2022-01-22
SELECT * FROM test;
id
ts
1
2022-01-01
2
2022-01-02
3
2022-01-15
4
2022-01-08
5
2022-01-22
fiddle

How to fix AFTER UPDATE Trigger

I created a User Point system for my website. The table looks like this:
user_id name article gallery description total
------------------------------------------------------------
1 joe 7 3 0 10
2 hary 3 5 5 13
3 ana 1 1 2 4
I need an AFTER UPDATE trigger that will make the update SUM in the column total when the value changes in the column, article, gallery or description
DELIMITER $$
CREATE TRIGGER total_trg
AFTER UPDATE point_system FOR EACH ROW
BEGIN
UPDATE point_system SET total = (article + gallery + description) FROM point_system WHERE user_id = NEW.user_id;
END
$$
DELIMITER ;
This trigger does not work. Why?
You cannot modify a table's contents from a trigger on that table (except for the row the trigger is operating on, but not in that way); in this case, what you need is a BEFORE UPDATE trigger, in which you would just
SET NEW.total = NEW.article + NEW.gallery + NEW.description;
You use NEW and OLD to access (and modify in BEFORE triggers) the field values of the row responsible for the trigger firing.

How to create a trigger on updating other table

I want to create table name birthrate that relates to the main table birth_t, so when I insert data to birth_t, automatically birthrate table will also be updated.
Birth_t fields:
Birth_id
Name
Birthplace
Birthdate
Sex
Height
Weight
Mother
Father
Birthrate fields:
Id
Year (from Birthdate field)
Sum (summing birth rate from the year, so we know how many babies that born in certain year)
How to create trigger for those?
You will need to get the year from Birthdate and check it against the records in the other table to update the applicable record. This is how you can do it:
delimiter |
CREATE TRIGGER birthrata_update BEFORE INSERT ON test1
FOR EACH ROW
BEGIN
insert into Birthrate(Year, Sum)
select New.Year, 0
from BirthRate
where not exists (select 1 from BirthRate BR where BR.Year = New.Year limit 0, 1 );
update Birthrate
set Sum = Sum + 1
where Birthrate.Year = YEAR(NEW.Birthdate);
END;
|
This trigger should insert a row to BirthRate if it did not exist with an initial value of 0. And then it will increment the Sum.

how to create trigger in mysql for insert data into table

Leave_applied_table:
leave_applied_id employee_id status start_date end_date_session hours
1 345 1 2016-6-25 2016-8-25 16
Leave_actula_table:
leave_applied_id leave_type_id hours created_at
345 2 16 2016-7-25
345 2 16 2016-7-25
345 2 16 2016-7-25
Leave_approval_table:
leave_approval_id leave_applied_id manger_id status
56 345 125 1
this is my three table i have to create triggger like when i insert in to Leave_applied then in leave_actual table three row should insert and in leave_approval_table in entry should come as given data in table please suggest me how to write query for this how to create trigger i am new in one this please suggest me for give issue .
Try it like this:
DELIMITER $$
CREATE TRIGGER insert_trigger
BEFORE INSERT ON Leave_applied_table FOR EACH ROW
begin
insert into Leave_actula_table (Leave_actula_table.leave_applied_id,and so ON....) values(new.employee_id,new.leave_type_id) ;
insert into Leave_approval_table (Leave_approval_table.leave_applied_id, and so on....) values (new.employee_id and so on;
END;
$$
DELIMITER ;
Hope it helps you as a guide..

insert data into one table from another table on specific condition

I have "table1" in which master data store like -
id name create_date validity expire_date
1 A 2015-08-01 3 2015-11-01
2 B 2015-09-01 12 2016-08-01
3 C 2015-09-15 1 2015-10-15
But now want to insert data in "table2" for expire_date according to validity period like without changing in front end. using trigger or procedure want to achieve this task.
id parent_id expire_date
1 1 2015-09-01
2 1 2015-10-01
3 1 2015-11-01
How can I achieve this using procedure or trigger.
It's hard to be specific because your question is not specific.
In general, here's the procedure to follow to design a query to insert stuff from one table into another.
First, write a SELECT query yielding a resultset containing the rows and columns you want inserted into your table. Use a list of columns to get the right columns, and appropriate WHERE clauses to get the right rows. Eyeball that query and that resultset to make sure it contains the correct information.
Second, prepend that debugged SELECT query with
INSERT INTO target_tablename (col, col, col)
Test this to make sure the correct rows are being inserted into your target table.
Third, create yourself an EVENT in your MySQL server to run the query you have just written. The event will, at the appropriate times of day, run your query.
If you take these steps out of order, you'll probably be very confused.
Can achieve the task using Store Procedure -
CREATE DEFINER=`root`#`localhost` PROCEDURE `addexpire`(IN uname varchar(50), IN cdate date, IN vm int)
BEGIN
insert into table1 (name,create_date,validity) values (uname,cdate,vm);
BEGIN
declare uparent_id INT;
declare v_val int default 0;
SET uparent_id = LAST_INSERT_ID();
while v_val < vm do
BEGIN
declare expire_date date;
SET expire_date = DATE_ADD(cdate,INTERVAL v_val+1 MONTH);
insert into table2 (parent_id,expire_date) values (uparent_id,expire_date);
set v_val=v_val+1;
END;
end while;
END;
END