Mysql auto insert a value after substraction - mysql

I am working on a car rental system. The table 'Hire' has fields like hireDate, returnDate, etc. I want to be able to calculate the rent and insert that value automatically into the database (same table).
I am wondering if I can subtract these two date fields, and the value which comes out of this can be multiplied by a certain number (say 300) and automatically added to another attribute called 'Rent_Due'. The idea is to calculate the total rent due by getting the number of days and then multiplying that by a certain number. So for every Hire that is made, I just enter the hiring date and the return date, and the Rent Due attribute is automatically filled. Is this possible by any chance?
I dont know what more information I need to provide to seek help, kindly let me know if you might require an image of my ERD.
Thanks!

Assuming the difference you want to compute in in days, this should work.
INSERT INTO yourTable (hireDate, returnDate, Rent_Due) VALUES
(StartDate. EndDate, DATEDIFF(EndDate, StartDate)*300)

Personally I would steer clear of having calculated fields in the database, and try to keep it normalized.
You could, instead, use a view for the duration of hire and hence the price.
Example as follows:
create view hire_duration as (
select hireId, hireDate, datediff(returnDate,hireDate) as duration
from Hire
);
(This assumes you have a primary key called hireId in your Hire table)
You could easily modify the view to have cost of hire as well, by multiplying duration by some constant, and that would be OK if the cost never changes, but if it you want to have the flexibility of different hire rates you wound't want to hard-code a rate in your SQL.

You don't required to create another field you can get your result be the following query.
select (datediff(hireDate, returnDate)*300) as rent,hireDate,returnDate from Hire;

Are you looking for maybe something like this?
Before-Insert-Event:
DELIMITER $$
CREATE TRIGGER name_of_before_insert_trigger BEFORE INSERT ON name_of_table
FOR EACH ROW BEGIN
SET NEW.Rent_Due = DATEDIFF(NEW.returnDate, NEW.hireDate) * 300;
END;
$$
DELIMITER ;
Before-Update-Event:
DELIMITER $$
CREATE TRIGGER name_of_before_update_trigger BEFORE UPDATE ON name_of_table
FOR EACH ROW BEGIN
SET NEW.Rent_Due = DATEDIFF(NEW.returnDate, NEW.hireDate) * 300;
END;
$$
DELIMITER ;
The daily rate you can also outsource in a separate table:
DELIMITER $$
CREATE TRIGGER name_of_before_insert_event_trigger BEFORE INSERT ON name_of_table
FOR EACH ROW BEGIN
SET NEW.Rent_Due = DATEDIFF(NEW.returnDate, NEW.hireDate) * (SELECT value FROM name_of_price_table LIMIT 1);
END;
$$
DELIMITER ;

Related

In MySQL, how do you change the value of a column in a table depending on an updated column in another table?

I'm attempting to create a trigger that increases the value of a column INCOME in the Salary database by 500 each time the value of WorkYear in the Employee table is increased by one year. For example, if the workYear is 4 and the salary is 1000, the salary should be 1500 if the workYear is increased by one year, 2000 if the workYear is increased by two years, and so on.
I tried to create such trigger and here is my code :
DELIMITER $$
create trigger increment AFTER UPDATE on employee
for each row
BEGIN
IF OLD.workYear <> new.workYear THEN
update salary
set income = (income + (new.workYear-old.workYear)*500);
END IF;
END$$
The idea behind this code is that after we update the workYear, the trigger should increase the salary by the difference of years * 500, (new.workYear-old.workYear)*500, but it increases all the rows by the same number, (5500 if we add one year, 27500 if we add two years, etc.) which not what we are looking for .
I am new to MySQL and would appreciate it if someone could assist me with this.
Thanks in advance
FaissalHamdi
In MySQL an AFTER trigger can affect the entire table, so you must declare the update scope in the form of criteria or a join.
Create Trigger in MySQL
To distinguish between the value of the columns BEFORE and AFTER the DML has fired, you use the NEW and OLD modifiers.
The concept is similar but each RDBMS has a slightly different syntax for this, be careful to search for help specifically on your RDBMS.
In the original query these special table references were used to evaluate the change condition however the scope of the update was not defined.
Assuming that there is a primary key field called Id on this salary table.
Also note that if you can, the query should be expressed in the form of a set-based operation, instead of static procedural script, this will be more conformant to other database engines.
So lets try this:
DELIMITER $$
create trigger increment AFTER UPDATE on employee
for each row
BEGIN
UPDATE salary s
SET income = (income + (new.workYear-old.workYear)*500)
WHERE s.Id = OLD.Id
END$$

MYSQL - Advice on populating FIELD options from another TABLE COLUMN using ENUM

I'm a MySql newbie so sorry if this has been asked before.
I am going round in circles trying to get a solution to this question.
I have a MySql database with two tables.
TERRITORIES
This table lists all nations of the world and has a column for listing the currency of each country.
CURRENCIES
This is essentially a "lookup" table including a country ID and a list of world currencies.
When inputting data into the TERRITORIES.currency cell I would like a drop-down list to appear from the CURRENCIES.country column.
I've spent hours googling to see if an ENUM field can call that data from the other table or whether one should use SET etc.
If anyone can assist me with reference to a good CLEAR tutorial on this issue I'd appreciate it.
There appear to be 2 things you want to happen 1) Populate 2) validate
For both triggers may be good for you.
delimiter $$
Create trigger t before insert on territories
for each row
begin
set new.currency = (Select currency from currencies where country = new.country);
end $$
delimiter ;
It doesn't then matter if an insert tries to insert to currency as well as country.
You also need an update trigger
delimiter $$
Create trigger t before update on territories
for each row
begin
set new.currency = (Select currency from currencies where country = new.country);
end $$
delimiter ;
To stop an update changing the currency to an invalid currency.

Creating Trigger on Insert Command MYSQL

I am trying to create a trigger for when someone enters a salary number that is less than a number already present in my database. I know how to make it in Java and C, just not in SQL.
CREATE TRIGGER InsertError
ON dbo.Employee_audit
AFTER Insert
AS
BEGIN
IF (SELECT Salary FROM dbo.Employee_audit) < 25000
BEGIN
RAISERROR('Salary is too low')
END
END
GO
I know this is incorrect, but there seems to be little resources or examples of specific scenarios.

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 :)

Is it possible to create a column in MySQL with an expression as a default value?

How would one implement this in MySQL:
CREATE TABLE employee (
employeemonthly DECIMAL(10,2),
employeeyearly DECIMAL(10,2) DEFAULT employeemonthly*12
);
use a insert trigger for that. Something like this
DELIMITER |
CREATE TRIGGER default_yearly BEFORE INSERT ON employee
FOR EACH ROW BEGIN
SET NEW.employeeyearly = NEW.employeemonthly * 12;
END;
|
DELIMITER ;
I would use a view:
CREATE VIEW vemployees AS
SELECT e.employeemonthly,
e.employeemonthly * 12 AS employeeyearly
FROM EMPLOYEE e
...because there's little need to dedicate storage space for an easily calculated value. Otherwise, use a function or simply write the expression into whatever query/stored procedure you need.
What really depends is:
How often you need to access this data
How complex the operation is to get the result you need
I recommend starting with not storing the value. If performance gets to be a problem, then dedicate a column for the values storage -- not before. At that, a trigger is a bit overkill to me, when you can use (psuedocode):
INSERT INTO employee
(...employeemonthly, employeeyearly, ...)
VALUES
(...#employeemonthly, #employeemonthly * 12, ...
Use a trigger for the insert event, access the new record data using NEW and set the appropiate values.