get previous field value in trigger mysql - mysql

I have a trigger like this in MySQL:
DELIMITER $$
CREATE TRIGGER service_before_update BEFORE UPDATE ON service
FOR EACH ROW
BEGIN
IF NEW.seatCount < (?) THEN
SIGNAL SQLSTATE '12345';
END IF;
END$$
DELIMITER ;
instead of (?) I want previous value of "seatCount" is there any easy way or I should use something like this(ServiceNo is a PRI key):
(SELECT seatCount FROM service WHERE serviceNo = NEW.serviceNo LIMIT 1)

Yeah, it's super easy. OLD.seatCount should do what you want. http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html has more information.

Related

Writing a before delete trigger to delete only based on count of attribute [duplicate]

If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?
As of MySQL 5.5, you can use the SIGNAL syntax to throw an exception:
signal sqlstate '45000' set message_text = 'My Error Message';
State 45000 is a generic state representing "unhandled user-defined exception".
Here is a more complete example of the approach:
delimiter //
use test//
create table trigger_test
(
id int not null
)//
drop trigger if exists trg_trigger_test_ins //
create trigger trg_trigger_test_ins before insert on trigger_test
for each row
begin
declare msg varchar(128);
if new.id < 0 then
set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));
signal sqlstate '45000' set message_text = msg;
end if;
end
//
delimiter ;
-- run the following as seperate statements:
insert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad
select * from trigger_test;
insert into trigger_test values (1); -- succeeds as expected
insert into trigger_test values (-1); -- fails as expected
select * from trigger_test;
Here is one hack that may work. It isn't clean, but it looks like it might work:
Essentially, you just try to update a column that doesn't exist.
Unfortunately, the answer provided by #RuiDC does not work in MySQL versions prior to 5.5 because there is no implementation of SIGNAL for stored procedures.
The solution I've found is to simulate a signal throwing a table_name doesn't exist error, pushing a customized error message into the table_name.
The hack could be implemented using triggers or using a stored procedure. I describe both options below following the example used by #RuiDC.
Using triggers
DELIMITER $$
-- before inserting new id
DROP TRIGGER IF EXISTS before_insert_id$$
CREATE TRIGGER before_insert_id
BEFORE INSERT ON test FOR EACH ROW
BEGIN
-- condition to check
IF NEW.id < 0 THEN
-- hack to solve absence of SIGNAL/prepared statements in triggers
UPDATE `Error: invalid_id_test` SET x=1;
END IF;
END$$
DELIMITER ;
Using a stored procedure
Stored procedures allows you to use dynamic sql, which makes possible the encapsulation of the error generation functionality in one procedure. The counterpoint is that we should control the applications insert/update methods, so they use only our stored procedure (not granting direct privileges to INSERT/UPDATE).
DELIMITER $$
-- my_signal procedure
CREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))
BEGIN
SET #sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');
PREPARE my_signal_stmt FROM #sql;
EXECUTE my_signal_stmt;
DEALLOCATE PREPARE my_signal_stmt;
END$$
CREATE PROCEDURE insert_test(p_id INT)
BEGIN
IF NEW.id < 0 THEN
CALL my_signal('Error: invalid_id_test; Id must be a positive integer');
ELSE
INSERT INTO test (id) VALUES (p_id);
END IF;
END$$
DELIMITER ;
The following procedure is (on mysql5) a way to throw custom errors , and log them at the same time:
create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;
DELIMITER $$
CREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))
BEGIN
DECLARE errorWithDate varchar(64);
select concat("[",DATE_FORMAT(now(),"%Y%m%d %T"),"] ", errorText) into errorWithDate;
INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);
INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);
END;
$$
DELIMITER ;
call throwCustomError("Custom error message with log support.");
CREATE TRIGGER sample_trigger_msg
BEFORE INSERT
FOR EACH ROW
BEGIN
IF(NEW.important_value) < (1*2) THEN
DECLARE dummy INT;
SELECT
Enter your Message Here!!!
INTO dummy
FROM mytable
WHERE mytable.id=new.id
END IF;
END;
Another (hack) method (if you are not on 5.5+ for some reason) that you can use:
If you have a required field, then within a trigger set the required field to an invalid value such as NULL. This will work for both INSERT and UPDATE. Do note that if NULL is a valid value for the required field (for some crazy reason) then this approach will not work.
BEGIN
-- Force one of the following to be assigned otherwise set required field to null which will throw an error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SET NEW.`required_id_field`=NULL;
END IF;
END
If you are on 5.5+ then you can use the signal state as described in other answers:
BEGIN
-- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';
END IF;
END
DELIMITER ##
DROP TRIGGER IF EXISTS trigger_name ##
CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
--the condition of error is:
--if NEW update value of the attribute age = 1 and OLD value was 0
--key word OLD and NEW let you distinguish between the old and new value of an attribute
IF (NEW.state = 1 AND OLD.state = 0) THEN
signal sqlstate '-20000' set message_text = 'hey it's an error!';
END IF;
END ##
DELIMITER ;

CREATE TRIGGER to monitor a specific table row

I have two tables & need to write a TRIGGER for this scenario.
1. Parameters_Table(int pkid, string param_name, string param_value)
2. Tokens_Table(int pkid,string item,string validity)
I have a requirement of deleting all entries in Tokens_Table if a particular row where param_name='Enterprise' in Parameters_Table changes its 'param_value'. The value is changed from UI. eg., row <7,enterprise,60> changes to <7,enterprise,25> in Parameters_Table then delete all entries from Tokens_Table.
How should I write the trigger. Please guide. (I need to write this for Informix Database, but mysql queries would also help)
DELIMITER $$
CREATE TRIGGER after_update AFTER UPDATE ON Parameters_Table
FOR EACH ROW
BEGIN
IF OLD.param_name ='Enterprise' THEN
IF NEW.param_value != OLD.param_value THEN
DELETE FROM Tokens_Table WHERE pkid = NEW.pkid;
END IF;
END IF;
END$$
Just try above code.Hope this will helps.
You can try the following syntax/format:
DELIMITER $$
CREATE TRIGGER delete_tokens AFTER INSERT ON Parameters_Table
FOR EACH ROW
BEGIN
IF NEW.param_name = 'enterprise' THEN
BEGIN
DELETE FROM Tokens_Table WHERE pkid = NEW.pkid;
END;
END IF;
END$$

how to use trigger for restricting modification

I have used this trigger to restrict the insertion of those records for which the date of birth is less then 18. This is working fine for the new insertion, but I also want to restrict the modification of the date of birth if it is set to less then 18. Please tell how can I do this?
DELIMITER $$
CREATE TRIGGER `test_candidate_before_insert` BEFORE INSERT ON `candidate` FOR EACH ROW
BEGIN
IF
DATEDIFF(CURDATE(), NEW.date_of_birth)/365 < 18
THEN
SIGNAL SQLSTATE '12345';
END IF;
END$$
DELIMITER ;
You need to define a separate UPDATE trigger.
MySQL, unfortunately, can't create trigger "before insert or update" like other common RDBMSs.
Just create another trigger for updating:
DELIMITER $$
CREATE TRIGGER `test_candidate_before_update` BEFORE UPDATE ON `candidate` FOR EACH ROW
BEGIN
IF
DATEDIFF(CURDATE(), NEW.date_of_birth)/365 < 18
THEN
SIGNAL SQLSTATE '12345';
END IF;
END$$
DELIMITER ;

How can i create a trigger to verify if a record exists on another table?

I am using version 5.0 of mysql.
I'm trying to create a trigger to check if one entry(name of Food) exists in the other table.
I´ve done this:
delimiter //
CREATE TRIGGER verifyExists BEFORE INSERT ON Sold
FOR EACH ROW
BEGIN
IF NEW.nameF not in (
select A.nameF
From Available D
where (NEW.nameF = A.nameF and NEW.nameR = A.nameR)
)
END IF;
END;
//
delimiter ;
this doesen't work, why?
You have a couple of errors:
delimiter //
CREATE TRIGGER verifyExists BEFORE INSERT ON Sold
FOR EACH ROW
BEGIN
IF NEW.nameF not in (
select A.nameF
From Available A -- CHANGED THE ALIAS TO A
where (NEW.nameF = A.nameF and NEW.nameR = A.nameR)
) THEN -- MISSING THEN
CALL `Insert not allowed`;
END IF;
END;
//
delimiter ;
sqlfiddle demo
If you could use SIGNAL, it is the best way, but since it was only introduced in mysql 5.5, you will have to do it by other route. One way is to call a non existant function, like showed above. From this answer

Throw an error preventing a table update in a MySQL trigger

If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?
As of MySQL 5.5, you can use the SIGNAL syntax to throw an exception:
signal sqlstate '45000' set message_text = 'My Error Message';
State 45000 is a generic state representing "unhandled user-defined exception".
Here is a more complete example of the approach:
delimiter //
use test//
create table trigger_test
(
id int not null
)//
drop trigger if exists trg_trigger_test_ins //
create trigger trg_trigger_test_ins before insert on trigger_test
for each row
begin
declare msg varchar(128);
if new.id < 0 then
set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));
signal sqlstate '45000' set message_text = msg;
end if;
end
//
delimiter ;
-- run the following as seperate statements:
insert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad
select * from trigger_test;
insert into trigger_test values (1); -- succeeds as expected
insert into trigger_test values (-1); -- fails as expected
select * from trigger_test;
Here is one hack that may work. It isn't clean, but it looks like it might work:
Essentially, you just try to update a column that doesn't exist.
Unfortunately, the answer provided by #RuiDC does not work in MySQL versions prior to 5.5 because there is no implementation of SIGNAL for stored procedures.
The solution I've found is to simulate a signal throwing a table_name doesn't exist error, pushing a customized error message into the table_name.
The hack could be implemented using triggers or using a stored procedure. I describe both options below following the example used by #RuiDC.
Using triggers
DELIMITER $$
-- before inserting new id
DROP TRIGGER IF EXISTS before_insert_id$$
CREATE TRIGGER before_insert_id
BEFORE INSERT ON test FOR EACH ROW
BEGIN
-- condition to check
IF NEW.id < 0 THEN
-- hack to solve absence of SIGNAL/prepared statements in triggers
UPDATE `Error: invalid_id_test` SET x=1;
END IF;
END$$
DELIMITER ;
Using a stored procedure
Stored procedures allows you to use dynamic sql, which makes possible the encapsulation of the error generation functionality in one procedure. The counterpoint is that we should control the applications insert/update methods, so they use only our stored procedure (not granting direct privileges to INSERT/UPDATE).
DELIMITER $$
-- my_signal procedure
CREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))
BEGIN
SET #sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');
PREPARE my_signal_stmt FROM #sql;
EXECUTE my_signal_stmt;
DEALLOCATE PREPARE my_signal_stmt;
END$$
CREATE PROCEDURE insert_test(p_id INT)
BEGIN
IF NEW.id < 0 THEN
CALL my_signal('Error: invalid_id_test; Id must be a positive integer');
ELSE
INSERT INTO test (id) VALUES (p_id);
END IF;
END$$
DELIMITER ;
The following procedure is (on mysql5) a way to throw custom errors , and log them at the same time:
create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;
DELIMITER $$
CREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))
BEGIN
DECLARE errorWithDate varchar(64);
select concat("[",DATE_FORMAT(now(),"%Y%m%d %T"),"] ", errorText) into errorWithDate;
INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);
INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);
END;
$$
DELIMITER ;
call throwCustomError("Custom error message with log support.");
CREATE TRIGGER sample_trigger_msg
BEFORE INSERT
FOR EACH ROW
BEGIN
IF(NEW.important_value) < (1*2) THEN
DECLARE dummy INT;
SELECT
Enter your Message Here!!!
INTO dummy
FROM mytable
WHERE mytable.id=new.id
END IF;
END;
Another (hack) method (if you are not on 5.5+ for some reason) that you can use:
If you have a required field, then within a trigger set the required field to an invalid value such as NULL. This will work for both INSERT and UPDATE. Do note that if NULL is a valid value for the required field (for some crazy reason) then this approach will not work.
BEGIN
-- Force one of the following to be assigned otherwise set required field to null which will throw an error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SET NEW.`required_id_field`=NULL;
END IF;
END
If you are on 5.5+ then you can use the signal state as described in other answers:
BEGIN
-- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';
END IF;
END
DELIMITER ##
DROP TRIGGER IF EXISTS trigger_name ##
CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
--the condition of error is:
--if NEW update value of the attribute age = 1 and OLD value was 0
--key word OLD and NEW let you distinguish between the old and new value of an attribute
IF (NEW.state = 1 AND OLD.state = 0) THEN
signal sqlstate '-20000' set message_text = 'hey it's an error!';
END IF;
END ##
DELIMITER ;