Creating Trigger on Insert Command MYSQL - 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.

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 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 auto insert a value after substraction

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 ;

Is there an equivalent for this trigger in stored procedures

I've been using this MySQL trigger on a dedicated server, so every time a table is updated, it calculates a new sum and updates another table:
delimiter |
CREATE TRIGGER after_insert_rep_points AFTER INSERT ON users_reputation
FOR EACH ROW
BEGIN
DECLARE new_total INT(10);
SELECT SUM(rep_points) INTO new_total FROM users_reputation
WHERE user_id = NEW.user_id;
UPDATE users SET rep_total = new_total WHERE user_id = NEW.user_id;
END
|
delimiter ;
I now need to use this on a shared hosting environment, but unfortunately, due to security precautions, I cannot have SUPER USER privileges in a shared environment, which is required for triggers. I don't understand this. I think everybody should be able to use triggers.
I'm not that clued up on stored procedures, in-fact I'm useless, but I'm wondering if this query can be executed using one and if so, can anybody can give me any pointers?
The person who wrote the trigger obviously has very limited SQL skills - the whole body can be expressed as a simple query:
UPDATE users SET
rep_total = (SELECT SUM(rep_points)
FROM users_reputation
WHERE user_id = users.user_id)
WHERE user_id = ?; -- "?" is NEW.user_id inside the trigger. You must provide it
You don't need a stored procedure - just run this query.

Call a Stored Procedure From a Stored Procedure and/or using COUNT

Ok, First off, I am not a mysql guru. Second, I did search, but saw nothing relevant related to mysql, and since my DB knowledge is limited, guessing syntactical differences between two different Database types just isn't in the cards.
I am trying to determine if a particular value already exists in a table before inserting a row. I've decided to go about this using two Stored procedures. The first:
CREATE PROCEDURE `nExists` ( n VARCHAR(255) ) BEGIN
SELECT COUNT(*) FROM (SELECT * FROM Users WHERE username=n) as T;
END
And The Second:
CREATE PROCEDURE `createUser` ( n VARCHAR(255) ) BEGIN
IF (nExists(n) = 0) THEN
INSERT INTO Users...
END IF;
END
So, as you can see, I'm attempting to call nExists from createUser. I get the error that no Function exists with the name nExists...because it's a stored procedure. I'm not clear on what the difference is, or why such a difference would be necessary, but I'm a Java dev, so maybe I'm missing some grand DB-related concept here.
Could you guys help me out by any chance?
Thanks
I'm not sure how it helped you, but...
why SELECT COUNT(*) FROM (SELECT * FROM Users WHERE username=n) and not just SELECT COUNT(*) FROM Users WHERE username=n?
Just make the user name (or whatever the primary application index is) a UNIQUE index and then there is no need to test: Just try to insert a new record. If it already exists, handle the error. If it succeeds, all is well.
It can (and should) all be one stored procedure.