I have very simple question but i did't get any simple code to exit from SP using Mysql.
Can anyone share with me how to do that?
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NULL THEN
#Exit this stored procedure here
END IF;
#proceed the code
END;
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
proc_label:BEGIN
IF tablename IS NULL THEN
LEAVE proc_label;
END IF;
#proceed the code
END;
If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by #piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).
As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more precise manner.
Here's how:
DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';
IF <Some Error Condition> THEN
SIGNAL CUSTOM_EXCEPTION
SET MESSAGE_TEXT = 'Your Custom Error Message';
END IF;
Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).
For more on this subject, check out:
https://dev.mysql.com/doc/refman/5.5/en/signal.html
How to raise an error within a MySQL function
http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html
Addendum
As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).
For example:
CALL AttemptedToInsertSomethingInvalid;
Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!
To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
CALL SP_Reporting_2(tablename);
END IF;
END;
CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
#proceed with code
END;
This works for me :
CREATE DEFINER=`root`#`%` PROCEDURE `save_package_as_template`( IN package_id int ,
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN
DECLARE v_pkg_name varchar(50) ;
DECLARE v_pkg_temp_id int(10) ;
DECLARE v_workflow_count INT(10);
-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;
this_proc:BEGIN -- this_proc block start here
IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;
select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;
END ;-- this_proc block end here
END
Why not this:
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
#proceed the code
END IF;
# Do nothing otherwise
END;
MainLabel:BEGIN
IF (<condition>) IS NOT NULL THEN
LEAVE MainLabel;
END IF;
....code
i.e.
IF (#skipMe) IS NOT NULL THEN /* #skipMe returns Null if never set or set to NULL */
LEAVE MainLabel;
END IF;
I think this solution is handy if you can test the value of the error field later. This is also applicable by creating a temporary table and returning a list of errors.
DROP PROCEDURE IF EXISTS $procName;
DELIMITER //
CREATE PROCEDURE $procName($params)
BEGIN
DECLARE error INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET error = 1;
SELECT
$fields
FROM $tables
WHERE $where
ORDER BY $sorting LIMIT 1
INTO $vars;
IF error = 0 THEN
SELECT $vars;
ELSE
SELECT 1 AS error;
SET #error = 0;
END IF;
END//
CALL $procName($effp);
Related
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 ;
How do I realize the following in MySQL with Triggers:
When value of some column is null -> set other column values to null
and
when value of some column is not null -> set other column values to null
table definition:
CREATE TABLE variations (
id int(10) NOT NULL,
x1 int(10) NOT NULL,
x2 int(10),
x1_option1 BOOL,
x2_option1 BOOL,
x1_option2 varchar(10),
x2_option2 varchar(10)
);
The idea is that we have 2 Elements, x1and x2. While x1is mandatory, x2is optional and can be null. Both, x1 and x2 have two options: x1_option1 , x2_option1, x1_option2 and x2_option2.
The first rule should be that when x2 is null, both options for x2 (x2_option1, x2_option2) must also be null.
My attempt:
CREATE
TRIGGER check_null_x2 BEFORE INSERT
ON variations
FOR EACH ROW BEGIN
IF NEW.x2 IS NULL THEN
SET NEW.x2_option1 = NULL;
SET NEW.x2_option2 = NULL;
END IF;
END$$
Throws Error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 6
Can you please help me figuring out whats wrong? I just dont understand what '' means.
The second rule should be that there can only be one of the two options selected. that means if x2_option1 is NOT NULL, x2_options2 must be NULL. In general i think this can be done the same way as the first rule. My question: how can i do multiple 'IF', 'ELSE IF' etc in one trigger?
This is syntax for trigger:
delimiter //
CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;//
delimiter ;
...and your code is here:
DELIMITER //
CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations
FOR EACH ROW
BEGIN
IF NEW.x2 IS NULL THEN
SET NEW.x2_option1 = NULL;
SET NEW.x2_option2 = NULL;
END IF;
END$$ -- THIS LINE SHOULD BE: "END;//"
DELIMITER ;
EDIT:
The official Documentation says the following:
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
To redefine the mysql delimiter, use the delimiter command. The following example shows how to do this for the dorepeat() procedure just shown. The delimiter is changed to // to enable the entire definition to be passed to the server as a single statement, and then restored to ; before invoking the procedure. This enables the ; delimiter used in the procedure body to be passed through to the server rather than being interpreted by mysql itself.
you seem to have ";" set as DELIMETER, which causes the query to execute once it sees a ";". try changing it first:
DELIMITER //
CREATE
TRIGGER check_null_x2 BEFORE INSERT
ON variations
FOR EACH ROW BEGIN
IF NEW.x2 IS NULL THEN
SET NEW.x2_option1 = NULL;
SET NEW.x2_option2 = NULL;
END IF;
END;//
DELIMITER ;
CREATE TRIGGER `XXXXXX` BEFORE INSERT ON `XXXXXXXXXXX` FOR EACH ROW BEGIN
IF ( NEW.aaaaaa IS NULL ) THEN
SET NEW.XXXXXX = NULL;
SET NEW.YYYYYYYYY = NULL;
END IF;
END
Worked for me....
I want to do sth like below .There is one procedure which contains two other procedures.
The first one inserts some date into my 'User' table and the second do the same to some other tables. The problem is , when I call this SP with a wrong 'CountryID' which leads the process to an error as expected, the first SP (InsertUsername) commits!
obviously what I want is having a roll back after this error .
BEGIN
START TRANSACTION ;
SET #Username = _Username;
CALL `InsertUsername` (
#Username , #UserID
);
CALL `InsertAddress` (
#UserID , _CountryID , _AdderssText , _PostalCode
);
COMMIT ;
END
I recently found that transactions didn't work as expected until we defined exit handlers in the stored procedures.
We created a fairly crude one-liner for use as a default:
declare exit handler for SQLWARNING, SQLEXCEPTION begin show warnings limit 5; rollback; end;
like simon.evans said I finally found the correct answer and it worked for me so I want to add more details :
CREATE PROCEDURE `add`(IN serial_number VARCHAR(20), IN tarnsaction_type INT
, OUT errcode VARCHAR(3))
BEGIN
DECLARE my_balance NUMERIC(15,3);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SET errcode = '058';
END;
CALL procedure2(p_account_id,v_account_balance);
#do what ever you want to do here
END$$
If you have a question ask me
because I had the same problem and finally I found this answer :)
With regards to using MySQL stored procedures with transactions, and I am having a problem getting error output.
The problem is that I need to set an exit_handler to roll back the transaction if anything fails. But when I do this, I don't get any error output if something goes wrong. For example if I accidentally pass a NULL value and try to insert it into a non-null field.
I am using a return value to programmatically indicate success or failure, however this does nothing to tell me what actually went wrong.
I am using Perl DBI to talk to MySQL. I am using MySQL 5.0.92 on the production server and MySQL 5.0.51a on the development server. Upgrading to a newer version of MySQL is politically untenable.
This is a simplified example:
DELIMITER //
CREATE PROCEDURE pmt_new(
app_id varchar(40),
out ret tinyint unsigned,
out pmt_req_id int(10) unsigned)
BEGIN
DECLARE v_pmt_req_type int(10) unsigned;
DECLARE exit handler for not found, sqlwarning, sqlexception rollback;
set ret=1;
START TRANSACTION;
SELECT pmt_type INTO v_pmt_req_type FROM pmt_req_types WHERE pmt_req_name = 'Name 1';
INSERT INTO pmt_reqs (pmt_req_id, pmt_req_type, app_id)
values (null, v_pmt_req_type, app_id);
set pmt_req_id = last_insert_id();
INSERT INTO other (pmt_req_id) values (pmt_req_id);
COMMIT;
set ret=0;
END//
DELIMITER ;
Instead of just doing a rollback in your exit handler you need to return something as well...
You currently have
DECLARE exit handler for not found, sqlwarning, sqlexception rollback;
Change it to something like...
DECLARE exit handler for not found, sqlwarning, sqlexception
begin
rollback;
select "We had to rollback, error!";
end;
In 5.5 they added the SIGNAL/RESIGNAL statements so you could 'return' an error but prior versions you have to kind of roll your own solution. If you need you can declare multiple exit handlers to tailor the output better, or setup your own error table you can pull from.
You can also do input testing inside your stored procedure. Want to know if app_id is null?
DELIMITER //
CREATE PROCEDURE pmt_new(
app_id varchar(40),
out result varchar(256),
out ret tinyint unsigned,
out pmt_req_id int(10) unsigned)
BEGIN
DECLARE v_pmt_req_type int(10) unsigned;
DECLARE exit handler for not found, sqlwarning, sqlexception rollback;
SET ret=1;
SET result = "";
IF app_id IS NULL THEN
set result = "Supplied ID is Null";
ELSE
START TRANSACTION;
SELECT pmt_type INTO v_pmt_req_type FROM pmt_req_types WHERE pmt_req_name = 'Name 1';
INSERT INTO pmt_reqs (pmt_req_id, pmt_req_type, app_id)
values (null, v_pmt_req_type, app_id);
set pmt_req_id = last_insert_id();
INSERT INTO other (pmt_req_id) values (pmt_req_id);
COMMIT;
set ret=0;
END IF;
END//
DELIMITER ;
Doing it this way adds another out parameter, but gives you much better information. You could do the same with multiple exit handlers.
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 ;