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

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 ;

Related

#1292 - Truncated incorrect DOUBLE value: '039c1a02-ecd3-405a-a745-136df5bbecbb

For the life of me I can't find the error in my code:
This is the code
INSERT INTO ce000
(guid,number,cedate,debit,credit,notes,currencyguid,currencyval,cesecurity,isposted,isprinted,typeguid,usguid)
VALUES
('039c1a02-ecd3-405a-a745-136df5bbecbb',
1331,
'2019-09-01',
50000,
200000,
'My First Entry',
'5a8fe466-d2c7-11e9-b2ad-54ab3a1011d7',
1,1,1,0,
'0x0',
'6d102621-d219-11e9-b2ad-54ab3a1011d7')
It throws me this error:
#1292 - Truncated incorrect DOUBLE value: '039c1a02-ecd3-405a-a745-136df5bbecbb
and here is the structure of the ce000 table:
1 guid char(38)
2 number int(11)
3 cedate datetime
4 debit float
5 credit float
6 notes varchar(255)
7 currencyguid char(38)
8 currencyval float
9 cesecurity int(11)
10 isposted int(11)
11 isprinted int(11)
12 typeguid char(38)
13 usguid char(38)
14 created_at datetime
Where is the error I can't find it?
Update:
Show create table ce000:
CREATE TABLE `ce000` (
`guid` char(38) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0',
`number` int(11) DEFAULT NULL,
`cedate` datetime DEFAULT NULL,
`debit` float DEFAULT NULL,
`credit` float DEFAULT NULL,
`notes` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`currencyguid` char(38) COLLATE utf8_unicode_ci DEFAULT NULL,
`currencyval` float DEFAULT NULL,
`cesecurity` int(11) DEFAULT NULL,
`isposted` int(11) DEFAULT NULL,
`isprinted` int(11) DEFAULT NULL,
`typeguid` char(38) COLLATE utf8_unicode_ci DEFAULT NULL,
`usguid` char(38) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`guid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Another Update:
The table ce000 has the following trigger which should fire only if the INSERT statement is missing the guid value, the table sets it to default 0 and the trigger should catch the 0 value and turn it ti uuid():
DELIMITER $$
CREATE TRIGGER `ce000_before_insert` BEFORE INSERT ON `ce000`
FOR EACH ROW BEGIN
IF new.guid = 0 THEN
SET new.guid = uuid();
END IF;
END$$
Oh my GOD
The problem is in the trigger
DELIMITER $$
CREATE TRIGGER `ce000_before_insert` BEFORE INSERT ON `ce000`
FOR EACH ROW BEGIN
IF new.guid = 0 THEN
SET new.guid = uuid();
END IF;
END$$
Since guid type is char(38) when I'm telling it if = 0 (without quotes) it doesn't work
so I only added the '0' text quotes to let mysql understand it as a string not INTEGER
GOD my brain is fried
by the way many thanks to GMB
DBFiddle.com is an amazing website, can't believe I didn't know about it before

While loop just stopped working after about 4 weeks without issue

I've been referencing and using a stored While Loop for no problems, daily for around 4 weeks. A few days ago it just stopped working.
Ive tried running this with different tables with no help.
DELIMITER $$
CREATE PROCEDURE sp_ukdatatable_route_loop (IN _date date)
BEGIN
SET #first = 1, #last = (
SELECT all_act
FROM ukdatatable_input_ops
WHERE date=_date
);
WHILE(#first <= #last)
DO
INSERT IGNORE INTO ukdatatable_input_daily (date)
VALUES (_date);
SET #first = #first + 1;
END WHILE;
END $$
The loop should lookup an integer from the table ukdatatable_input_ops and then run the loop, creating (new) the number of rows that is equal to the integer returned from the table in another table ukdatatable_input_daily
Is anyone able to help?
Tables involved;
CREATE TABLE `ukdatatable_input_daily` (
 `entry_id` int(10) NOT NULL AUTO_INCREMENT,
 `date` date DEFAULT NULL,
 `aaa` varchar(25) DEFAULT NULL,
 `bbb` varchar(50) DEFAULT NULL,
 `ccc` varchar(25) DEFAULT NULL,
 `ddd` varchar(25) DEFAULT NULL,
 `eee` varchar(25) DEFAULT NULL,
 `arrival_time` time DEFAULT NULL,
 `departure_time` time DEFAULT NULL,
 `comments` text,
 `status` varchar(10) NOT NULL DEFAULT 'edit',
 `day` varchar(10) NOT NULL,
 PRIMARY KEY (`entry_id`)
) ENGINE=InnoDB AUTO_INCREMENT=156856 DEFAULT CHARSET=utf8mb4
CREATE TABLE `ukdatatable_input_ops` (
 `entry_id` int(10) NOT NULL AUTO_INCREMENT,
 `date` date DEFAULT NULL,
 `fff` time DEFAULT NULL,
 `ggg` int(10) DEFAULT NULL,
 `hhh` int(10) DEFAULT NULL,
 `iiil` int(10) DEFAULT NULL,
 `jjj` int(10) NOT NULL,
 `all_act` int(10) DEFAULT NULL,
 PRIMARY KEY (`entry_id`),
 UNIQUE KEY `date` (`date`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8mb4

How to create trigger for broken cars using IF statement

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 ;

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.

update another table when updated mysql trigger

I have 2 tables, students and Math. I want to UPDATE existing data on Math.Last_name when I update the students.Last_Name using the ID I am updating in students.
Students table
CREATE TABLE `STUDENTS` (
`Date_Modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`LRN` BIGINT(12) NOT NULL AUTO_INCREMENT,
`Last_Name` VARCHAR(50) NOT NULL,
`First_Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`LRN`)
)COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=123456789112;
MATH TABLE
CREATE TABLE `Math` (
`Date_Modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`LRN` BIGINT(12) NOT NULL,
`Last_Name` VARCHAR(50) NOT NULL,
`First_Name` VARCHAR(50) NOT NULL,
`Level` VARCHAR(3) NOT NULL,
`UT1` VARCHAR(3) NOT NULL,
`Q1` VARCHAR(50) NULL DEFAULT NULL,
`UT2` VARCHAR(50) NULL DEFAULT NULL,
`Q2` VARCHAR(50) NULL DEFAULT NULL,
`UT3` VARCHAR(50) NULL DEFAULT NULL,
`Q3` VARCHAR(50) NULL DEFAULT NULL,
`UT4` VARCHAR(50) NULL DEFAULT NULL,
`Q4` VARCHAR(50) NULL DEFAULT NULL,
`FINAL GRADE` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`LRN`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=COMPACT;
MY TRIGGER
CREATE TRIGGER `STUDENTS_after_update` AFTER UPDATE ON `STUDENTS` FOR EACH ROW BEGIN
UPDATE Math
SET Last_Name = NEW.Last_Name
WHERE LRN IN (SELECT LRN FROM Math where LRN = NEW.LRN);
END
You do not need a sub select in the update command, since for each row it will pick up the new LRN value and will update all of them in the MATH table where the new.LRN matches in the MATH table. Here how the trigger would look like
delimiter //
create trigger `STUDENTS_after_update` after update on `STUDENTS`
for each row
begin
update Math
set Last_Name = NEW.Last_Name
where LRN = NEW.LRN ;
end;//
delimiter ;
Note that I have added delimiter which is needed when you run them in the Mysql CLI, some other user interface like PHPMyadmin you need to select the delimiter from the user interface.