How to create trigger for broken cars using IF statement - mysql

I want to create a trigger that will not allow to rent a car if it is currently being repaired. Im quite new in triggers... could anyone shed some light on this aspect of triggers? My assumptions would be that it would something like...
DELIMITER $$
CREATE TRIGGER `inspections_const` BEFORE UPDATE ON `inspections` FOR EACH ROW BEGIN
SET NEW.booking_id = IF.repair_complete = 'No'
THEN 'Allow booking'
ELSE 'Do not allow'
END;
END
$$
DELIMITER ;
Table is
CREATE TABLE `inspections` (
`inspection_id` int(10) NOT NULL,
`inspection_date` date NOT NULL,
`vehicle_id` int(10) NOT NULL,
`problem` varchar(50) NOT NULL,
`repair_complete` enum('Yes','No') NOT NULL,
`mechanic_id` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `bookings` (
`booking_id` int(50) NOT NULL,
`booking_date` date NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`invoice_no` int(10) NOT NULL,
`chauffeur_id` int(10) DEFAULT NULL,
`vehicle_id` int(10) NOT NULL,
`customer_id` int(50) NOT NULL,
`chauffeur_req` enum('Yes','No') NOT NULL,
`special_instructions` varchar(255) NOT NULL,
`TheDuration` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I didn't tested it so it might have a missing condition or something like that. But it should help you on the correct path
Query
DELIMITER $$
CREATE TRIGGER `check_repair` BEFORE INSERT ON `bookings` FOR EACH ROW BEGIN
# We need to save the "count"
DECLARE inspections_count INT DEFAULT 0;
# Check if where is a repair going which matches the vehicle_id
SELECT
1 INTO inspections_count # store the "count" into the variable.
FROM inspections
WHERE
inspections.vehicle_id = NEW.vehicle_id
AND
repair_complete = 'No'
ORDER BY
inspections.start_date DESC
LIMIT 1;
# if there is a "count" stop the insert.
IF inspections_count = 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'vehicle is in repair';
END IF;
END
$$
DELIMITER ;

Related

MySQL - Trigger for updating same table after insert comparing the text

Need Help with MYSQL Trigger with IF TEXT contains condition
Here's what I'm trying to do on MYSQL:
When there's an update on the table (i,e) when the "status" is changed from 'open' to "closed", i want to update date_closed to current date.
Trigger with if condition {could not get it to work}
create TRIGGER update_close_date BEFORE UPDATE ON issues
FOR EACH ROW
BEGIN
if LOCATE('closed', NEW.status) !=0 THEN
SET new.date_closed = CURRENT_DATE;
end if;
END;
Table Structure
CREATE TABLE `issues` (
`id` int(10) NOT NULL,
`project_type` varchar(100) NOT NULL,
`assessment_name` varchar(150) NOT NULL,
`issue_title` varchar(200) NOT NULL,
`description` varchar(1000) DEFAULT NULL,
`severity` varchar(10) DEFAULT NULL,
`status` varchar(25) DEFAULT NULL,
`found_on` date DEFAULT NULL,
`target_date` date DEFAULT NULL,
`app_support_contact` varchar(100) DEFAULT NULL,
`manager` varchar(100) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
`date_updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`date_closed` date DEFAULT NULL,
`reminder_count` int(5) DEFAULT 0,
`escalation_count` int(5) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Update
Thanks for the support, figured out whats wrong, had to add Delimiter word :)
DELIMITER //
create TRIGGER update_close_date BEFORE UPDATE ON issues
FOR EACH ROW
BEGIN
if LOCATE('closed', NEW.status) !=0 THEN
SET new.date_closed = CURRENT_DATE;
end if;
END;//
DELIMITER ;

Process Multiple Row by a MYSQL Store Procedure

I am facing some trouble inserting data into a table by Store Procedure. Please allow me to explain in details.
I have a Three tables
CREATE TABLE `table_1` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`s_id` INT(11) NOT NULL,
`created` DATE NOT NULL,
`val` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
CREATE TABLE `table_2` (
`s_id` INT(11) NOT NULL AUTO_INCREMENT,
`t_id` INT(11) NOT NULL,
`p_id` INT(11) NOT NULL,
`d_id` INT(11) NOT NULL,
`created` DATE NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
CREATE TABLE `table_3` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`count` INT(11) NOT NULL,
`created` DATE NOT NULL,
`s_id` VARCHAR(255) NOT NULL,
`t_id` VARCHAR(255) NOT NULL,
`p_id` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
Is there any way to insert into 2nd table by store procedure using select statement. There will be multiple data as Select * from table_1; Then there will be a process like if(table_1.s_id == table_3.s_id) THEN UPDATE table_3 set count = count +1 ELSE INSERT into table_3 (s_id,t_id.....
Though I have tried using Cursor but its inserting only one record.
Here are the example of my usage of Cursor
DECLARE done INT DEFAULT FALSE;
DECLARE curs_count INT(11) DEFAULT 0;
DECLARE v_s_id BIGINT(20) DEFAULT 0;
DECLARE v_t_id BIGINT(20) DEFAULT 0;
DECLARE v_p_id BIGINT(20) DEFAULT 0;
DECLARE v_t_date BIGINT(20) DEFAULT 0;
DECLARE co_s_id BIGINT(20) DEFAULT 0;
DECLARE curs CURSOR FOR
SELECT
a.id,b.s_id,b.t_id,b.created
FROM
table_1 a
INNER JOIN table_2 b ON a.s_id = b.s_id
WHERE
a.val <> '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE curs_id INT(11) DEFAULT 0;
OPEN curs;
SELECT FOUND_ROWS() INTO curs_count;
start_loop: loop
FETCH curs INTO curs_id,v_s_id,v_t_id,v_c_date;
IF done THEN
LEAVE start_loop;
END IF;
SELECT s_id INTO co_s_id FROM table_3;
IF co_s_id>0
THEN
update table_3 SET count = count+1 where s_id = co_s_id;
ELSE
INSERT INTO table_3 (support_id,track_id,track_date,count) VALUES (v_s_id,v_t_id,v_c_date,1);
END IF;
end loop;
CLOSE curs;
Can anyone help me out with this?
This code is running properly. The issue was infinite loop made the tables corrupted so no data were inserting.

MySQL AFTER UPDATE in a specific column UPDATE timestamp in same row

I want to update the timestamp 'lastpageview_at', when the pageviews increases. I think I'm close but I always get a syntax error, does anybody know why or have an other solution?
My trigger:
CREATE TRIGGER Update_lastpageview BEFORE UPDATE ON shortlinks
FOR EACH ROW BEGIN
IF OLD.pageviews <=> NEW.pageviews THEN
SET NEW.lastpageview_at = CURRENT_TIMESTAMP();
END IF;
END;
Here is my table:
CREATE TABLE `shortlinks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`shortlink_id` varchar(40) NOT NULL DEFAULT '',
`pageviews` int(11) unsigned DEFAULT NULL,
`lastpageview_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `shortlink` (`shortlink`)
) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8;
inequality operator is either != or <> not <=>
delimiter $$
CREATE TRIGGER Update_lastpageview BEFORE UPDATE ON shortlinks
FOR EACH ROW BEGIN
IF OLD.pageviews <> NEW.pageviews THEN
SET NEW.lastpageview_at = NOW();
END IF;
END;$$

Trigger for inserting and updating multiple records in the same table in MySQL

I have table
CREATE TABLE `seniority_master` (
`EMPNO` varchar(4) NOT NULL,
`NAME` varchar(40) DEFAULT NULL,
`GENDER` varchar(10) DEFAULT NULL,
`CATGRY` varchar(10) DEFAULT NULL,
`DOB` date DEFAULT NULL,
`DESG` varchar(40) DEFAULT NULL,
`DESGTYPE` varchar(100) DEFAULT NULL,
`SENIORITY` int(4) NOT NULL,
`EMPTYPE` varchar(45) DEFAULT NULL,
`TYPE` varchar(45) DEFAULT NULL,
`QUAL` varchar(200) DEFAULT NULL,
`BRANCH` varchar(30) DEFAULT NULL,
`DOJ` date DEFAULT NULL,
`DOCA` date DEFAULT NULL,
`PAYSCALE` varchar(45) DEFAULT NULL,
`OTHERDESC` varchar(45) DEFAULT NULL,
PRIMARY KEY (`EMPNO`,`SENIORITY`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `seniority_master` VALUES ('1389','MUNNA','Male','OBC','1959-10-31','SENIOR RECORD SORTER (ASS-I)','',2,'STAFF','P03','4th','AGRA','1982-07-01','2007-07-01','12100-24500','');
INSERT INTO `seniority_master` VALUES ('1391','RAJENDER SINGH','MALE','UR','1965-07-09','AM (GENERAL)','GENERAL',40,'OFFICERS','H1','INTER ','AGRA','1984-06-22','2013-09-05','16400-40500','');
INSERT INTO `seniority_master` VALUES ('1392','MADAN GOPAL','Male','OBC','1966-07-04','SENIOR OFFICE MANAGERS-I (GENERAL)','',6,'STAFF','L1','10TH','AGRA','1984-08-17','2015-04-17','15600-30500','');
In the above data the seniority(2,40,6) of the employee is going to change every time when the promotion takes place based on the type(P03,H1,L1) of the employee.
What we really need is a Trigger that updates the seniority of all the other employees for the type when one of the employee is updated or inserted or deleted.
Ex: Suppose empno 4620 has seniority 5 and type A1, when we delete the particular empno in seniority_master table, the seniority of below employees of the same type to be updated automatically by increment or decrement based on the seniority. Similar procedure for updation and insertion operations to done.
I am able to create AFTER INSERT and AFTER UPDATE triggers for my program requirement.
DELIMITER $$
CREATE TRIGGER after_seniority_insert
AFTER INSERT ON seniority_master
FOR EACH ROW
BEGIN
INSERT INTO emp_positions
( empno,
position,
dop)
VALUES
( NEW.empno,
NEW.desg,
NEW.doca );
END$$
DELIMITER ;
After update:
DELIMITER $$
CREATE TRIGGER after_seniority_update
AFTER UPDATE ON seniority_master
FOR EACH ROW
BEGIN
IF (old.desg != new.desg &&
old.doca != new.doca) then
INSERT INTO emp_positions
( empno,
position,
dop)
VALUES
( NEW.empno,
NEW.desg,
NEW.doca );
END IF;
END$$
DELIMITER ;
Help me out for above scenario for creating trigger.

How to insert a record in MySQL table if a condition exists in a trigger

BLUF: I want to use a before insert trigger to prevent invalid data from being inserted, and instead store that data in another table with an error message for reviewing later.
I have a table in which my Raspberry Pi weather station is recording weather data. Sometimes it has a hardware failure for various reasons, and when that happens it returns -1000 for that particular data point.
I have tried to write a before insert trigger that would prevent these records from being written to the table with other valid data. This part seemed to work. But I would like to also write these erroneous records to a different table. While testing, bad data is rejected as expected, but no records are being written to the error log table.
Here is the trigger I have written:
DROP TRIGGER IF EXISTS wx_beforeInsert;
SET #ERROR_MESSAGE = '';
DELIMITER $$
CREATE TRIGGER `wx_beforeInsert` BEFORE INSERT ON WEATHER_MEASUREMENT
FOR EACH ROW BEGIN
IF (NEW.AMBIENT_TEMPERATURE = '-1000') THEN
SET #ERROR_MESSAGE = "Ambient tempurature invalid. Record rejected.";
ELSEIF (NEW.GROUND_TEMPERATURE = '-1000') THEN
SET #ERROR_MESSAGE = "Ground tempurature invalid. Record rejected.";
ELSEIF (NEW.AIR_QUALITY = '-1000') THEN
SET #ERROR_MESSAGE = "Air quality invalid. Record rejected.";
ELSEIF (NEW.AIR_PRESSURE = '-1000') THEN
SET #ERROR_MESSAGE = "Air pressure invalid. Record rejected.";
ELSEIF (NEW.HUMIDITY = '-1000') THEN
SET #ERROR_MESSAGE = "Humidity invalid. Record rejected.";
END IF;
IF (#ERROR_MESSAGE <> '') THEN
INSERT INTO `weather`.`WEATHER_MEASUREMENT_ERRORS`
(`AMBIENT_TEMPERATURE`,
`GROUND_TEMPERATURE`,
`AIR_QUALITY`,
`AIR_PRESSURE`,
`HUMIDITY`,
`WIND_DIRECTION`,
`WIND_SPEED`,
`WIND_GUST_SPEED`,
`RAINFALL`,
`CREATED`,
`ERROR_MESSAGE`)
VALUES
(NEW.AMBIENT_TEMPERATURE,
NEW.GROUND_TEMPERATURE,
NEW.AIR_QUALITY,
NEW.AIR_PRESSURE,
NEW.HUMIDITY,
NEW.WIND_DIRECTION,
NEW.WIND_SPEED,
NEW.WIND_GUST_SPEED,
NEW.RAINFALL,
NEW.CREATED,
#ERROR_MESSAGE);
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = #ERROR_MESSAGE;
END IF;
END;
$$
Here is the script needed to create the supporting tables for anyone who would like to try to help:
CREATE DATABASE IF NOT EXISTS `weather` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `weather`;
-- Create the WEATHER_MEASUREMENT table if it doesn't exist
CREATE TABLE IF NOT EXISTS `WEATHER_MEASUREMENT` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`REMOTE_ID` bigint(20) DEFAULT NULL,
`AMBIENT_TEMPERATURE` decimal(6,2) NOT NULL,
`GROUND_TEMPERATURE` decimal(6,2) NOT NULL,
`AIR_QUALITY` decimal(6,2) NOT NULL,
`AIR_PRESSURE` decimal(6,2) NOT NULL,
`HUMIDITY` decimal(6,2) NOT NULL,
`WIND_DIRECTION` decimal(6,2) DEFAULT NULL,
`WIND_SPEED` decimal(6,2) NOT NULL,
`WIND_GUST_SPEED` decimal(6,2) NOT NULL,
`RAINFALL` decimal(6,4) DEFAULT NULL,
`CREATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4126 DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `WEATHER_MEASUREMENT_ERRORS` (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`REMOTE_ID` bigint(20) DEFAULT NULL,
`AMBIENT_TEMPERATURE` decimal(6,2) NOT NULL,
`GROUND_TEMPERATURE` decimal(6,2) NOT NULL,
`AIR_QUALITY` decimal(6,2) NOT NULL,
`AIR_PRESSURE` decimal(6,2) NOT NULL,
`HUMIDITY` decimal(6,2) NOT NULL,
`WIND_DIRECTION` decimal(6,2) DEFAULT NULL,
`WIND_SPEED` decimal(6,2) NOT NULL,
`WIND_GUST_SPEED` decimal(6,2) NOT NULL,
`RAINFALL` decimal(6,4) DEFAULT NULL,
`CREATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ERROR_MESSAGE` varchar(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4126 DEFAULT CHARSET=latin1;
I think your insert in WEATHER_MEASUREMENT_ERRORS ia rolled back, too.
Try to make WEATHER_MEASUREMENT_ERRORS nontransactional(ROLLBACK doesn't apply to nontransactional tables) by making it an MyISAM-Table.