Trigger errors mysql - mysql

I want to make a trigger that prevent inserting overlaping dates. For example:
If I have an offer "Oferta" with the date from 1/3/2016 to 5/3/2016, I can't insert a new offer with the date 2/3/2016 to 4/3/2016 or 4/3/2016 to 7/3/2016
My SELECT checks that condition I believe. What I don't know how to do is to make an error if such happens. I'm new to triggers and Im having syntax errors, I checked triggers syntax but couldnt find the problem...
DELIMITER $$
CREATE TRIGGER tri_check_date_overlap BEFORE INSERT ON Oferta
FOR EACH ROW
BEGIN
IF EXISTS(
SELECT * FROM Oferta WHERE
(new.morada = morada AND new.codigo = codigo
AND ((new.data_inicio BETWEEN data_inicio AND data_fim)
OR new.data_fim BETWEEN data_inicio AND data_fim)
)
)
/*CALL raise_application_error(3001, 'Not odd number!'); */
DECLARE msg varchar(255);
set msg = concat('Error: That right is not allowed!', cast(new.right as char));
signal sqlstate '45000' set message_text = msg;
END $$
DELIMITER ;

Your logic is ok, I think you just missed the 'then' condition after 'if' and 'end if' before the end of the trigger.

Related

MySQL error code #1064 near IF ELSE block when creating a Trigger Before Insert

I am trying to put a constraint on a database where if generic_asset.type = 'raw' then generic_asset.atomic = 1 must be maintained. For this I wrote the following trigger of type BEFORE INSERT. Here is the snippet:
DELIMITER //
CREATE TRIGGER generic_asset_check BEFORE INSERT ON generic_asset FOR EACH ROW
BEGIN
IF NEW.type = 'raw' THEN
BEGIN
IF NEW.atomic = 0 THEN
SET SQLSTATE = 'Sorry cannot insert';
END IF;
END IF;
END //
DELIMITER ;
Error is like:
#1064 - syntax error near 'SQLSTATE = 'Sorry cannot insert';
END IF;
END IF;
END' in line 6
(translated from French).
I tried various syntax but all seam not to work and also knowing that my changes are so little like changing double quotes, removing BEGIN with END IF;... So I know these turns are irreverent.
I revised syntax in many internet resources and official documentation, nothing helped.
MySQL's IF statement does not take a BEGIN keyword. Also, if you want to raise an error from within the trigger, you need SIGNAL. Finally, these two nested conditions can be flattened.
Consider:
DELIMITER //
CREATE TRIGGER generic_asset_check BEFORE INSERT ON generic_asset FOR EACH ROW
BEGIN
IF NEW.type = 'raw' AND NEW.atomic = 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Sorry cannot insert';
END IF;
END //
DELIMITER ;
Demo on DB Fiddle

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 ;

mysql weird trigger errors

I'm trying to set up a trigger (run from a separate .sql file) to prevent insertion like this:
create trigger insert_formulas before insert on formulas
for each row
if ((new.formula_id_1 is not null) and (new.semantic_id_1 is not null))
or ((new.formula_id_2 is not null) and (new.semantic_id_2 is not null))
then
signal sqlstate '45100';
set #message_text = 'A formula cannot be a definition at the same time';
end if;
It produces an error 1064 near '' at line 6 and near 'end if' at line 1. What have I done wrong?
Thanks in advance.
Does the 9.4. User-Defined Variables #message_text is different from MESSAGE_TEXT from the definition of 13.6.7.5. SIGNAL Syntax?
The following code creates the trigger correctly:
DELIMITER $$
CREATE TRIGGER `insert_formulas` BEFORE INSERT ON `formulas`
FOR EACH ROW
BEGIN
IF((NEW.`formula_id_1` IS NOT NULL AND NEW.`semantic_id_1` IS NOT NULL) OR
(NEW.`formula_id_2` IS NOT NULL AND NEW.`semantic_id_2` IS NOT NULL)) THEN
SIGNAL SQLSTATE '45100'
SET MESSAGE_TEXT = 'A formula cannot be a definition at the same time';
END IF;
END$$
DELIMITER ;
Here SQL Fiddle.

Mysql Prevent insert with insert trigger condition not met

I am trying to setup a trigger so an insert does not occur if a condition is not met.
I thought the below was the way to do it but i am not sure
I am getting an error
/* SQL Error (1407): Bad SQLSTATE: '45000 ' */
Can anyone let me know why I am getting this error and the best way for me to prevent an insert if the condition is not met in mysql.
DELIMITER $$
SHOW WARNINGS$$
USE `warrington_central`$$
CREATE TRIGGER before_insert_image_comment_section_check
BEFORE INSERT ON image_comment FOR EACH ROW
BEGIN
DECLARE error_msg varchar(255);
IF New.section != (SELECT id from section where section = "image")
THEN SET error_msg = "Cannot insert a comment into this section as it is the wrong section type";
SIGNAL SQLSTATE '45000 'SET MESSAGE_TEXT = error_msg;
END IF;
END
$$
SHOW WARNINGS$$
SQLSTATE is required to be a a 5 character string unless previously declared using DECLARE ... CONDITION;
SIGNAL SQLSTATE '45000 'SET MESSAGE_TEXT = error_msg;
You're trying to set SQLSTATE to '45000 ' (note the space) which is 6 characters long. Fix the spacing and you should not see the message again (it is also reflected in your error message, but the space is a bit hard to see)

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 ;