If-statement in the MySQL stored procedure for selecting data - mysql

I have the next SQL code:
DELIMITER $$
CREATE PROCEDURE `test`.`new_procedure` (queryString VARCHAR(255))
BEGIN
SELECT #tempValue = COUNT(*) FROM test.userdata_extended WHERE inn LIKE queryString;
IF #tempValue > 0 SELECT * FROM test.userdata_extended WHERE inn LIKE queryString;
END $$
I'm putting the COUNT* result into #tempValue variable.
Then I'm trying to compare it for being greater than zero.
I'm getting error with the statement comparing process. MySQL reports me a UNEXPECTED SELECT SYM error. What does it mean?
Also this would be a check for another tables. I need IF-ELSE statements, because basing on several query result my procedure must return the exact code error value (which could be different) for the my developed application to handle or giving the data, if all is fine.
How to fix this issue?
Thanks

You have forgot the THEN in your if statement. You need to add the THEN.
Like this:
IF #tempValue > 0 THEN ...your statement
END IF;
You have also forgot to add the END IF; add this also.
Reference site is here.

You forgot THEN and END IF;
IF #tempValue > 0 THEN
SELECT * FROM test.userdata_extended WHERE inn LIKE queryString;
END IF;

Related

MySQL update procedure WITH multiple CASE and WHERE

the query works and updates as it supposed to, but when I tried to make it into a stored procedure, it fails with "error near WHERE". Can anyone see what is wrong please?
DELIMITER //
DROP procedure if exists update_trans_with_tags//
CREATE PROCEDURE update_trans_with_tags()
BEGIN
UPDATE transactions
SET trans_cat = CASE WHEN trans_desc LIKE '%abc%' THEN 1
WHEN trans_desc LIKE '%def%' THEN 2
WHEN trans_desc LIKE '%ghi%' THEN 4
ELSE trans_cat
END;
WHERE trans_cat IS NULL;
END//
DELIMITER ;
Take the ; off of the first END; ; still terminates statements within the stored procedure. If the hanging WHERE didn't prevent you from saving the procedure; the "first" statement would UPDATE all transactions.

How to run simple stored procedure in mysequel pro or mysql workbench

I try to run this, but I get error.
set #var1 = 'AAA' ;
IF #var1 = 'AAA' THEN
Select * from List limit 2
END IF;
I am trying to run this in MAC's MySequel Pro, or Mysql Workbench.
I get syntax error. Can't say why.
I am not very familiar with stored procedure syntax.
Google search also not helped.
Do I use a ; End BEGIN, ??? tried all, but no luck.
How is the syntax, when I should use ;
When I should use Begin and END ??
Appreciate your help.
IF #var1 == 'AAA' THEN is wrong and so is the syntax error. It should just be below. Your's is not a compound statement and thus don't need a Begin .. end block. Refer MySQL Documentation On IF Syntax
IF #var1 = 'AAA' THEN
Select * from List limit 2
END IF;
Your SQL statement missing a semicolon at the end. It should be:
Select * from List limit 2;
And this just for a sample of stored procedure:
delimiter $$
use `your_database`$$
drop procedure if exists `SP_Name`$$
create definer=`root`#`localhost` procedure `SP_Name`()
begin
set #var1 = 'AAA';
IF #var1 = 'AAA' THEN
Select * from List limit 2;
END IF;
end$$
delimiter ;
For more info, check MySQL Documentation or MySQL Stored Procedure Tutorial example

Mysql - How to quit/exit from stored procedure

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);

SQL syntax error when creating a stored procedure in MySQL

I have a hard time locating an error when trying to create a stored procedure in mysql.
If I run every single line of the procedure independently, everything works just fine.
CREATE PROCEDURE cms_proc_add_child
(
param_parent_id INT, param_name CHAR(255),
param_content_type CHAR(255)
)
BEGIN
SELECT #child_left := rgt FROM cms_tree WHERE id = param_parent_id;
UPDATE cms_tree SET rgt = rgt+2 WHERE rgt >= #child_left;
UPDATE cms_tree SET lft = lft+2 WHERE lft >= #child_left;
INSERT INTO cms_tree (name, lft, rgt, content_type) VALUES
(
param_name,
#child_left,
#child_left+1,
param_content_type
);
END
I get the following (helpful) error:
ERROR 1064 (42000): 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 3
I just don't know where to start debugging, as every single one of these lines is correct.
Do you have any tips?
As line 3 contains the first ; perhaps you have a problem with your delimiters.
See http://dev.mysql.com/doc/refman/en/stored-programs-defining.html
DELIMITER //
CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
SET #x = 0;
REPEAT SET #x = #x + 1; UNTIL #x > p1 END REPEAT;
END//
DELIMITER ;
Thanks, near '' at line 3 was my problem and the delimiter statement fixed it! I always want things to make sense and this does. As the '' indicates it's at the end of the procedure, but no END statement was found thus the syntax error. And I wondered why I kept seeing a lot of people using the delimiter statement. I see the light!
You never declare your #child_left variable.
If you having issues with a bunch of Procedure that can't run at the same time but can run successfully alone, Try separate them with Go command.
Ex:
--i)
CREATE PROCEDURE A
AS
BEGIN
END;
GO
--ii)
CREATE PROCEDURE B
AS
BEGIN
END;

Triggers and stored proc in MySQL

I used MSSQL stored procedures and triggers for a while; MySQL is getting me absolutely crazy about how to write even the simpler procedure.
Why I get a syntax error in this so stuoid trigger?
CREATE TRIGGER set_prio_default BEFORE INSERT ON categories
FOR EACH ROW
BEGIN
set #my_prio := 1;
SET new.prio := #my_prio;
END
In facts this TRIGGER is an oversemplification of:
DELIMITER $$
DROP PROCEDURE IF EXISTS `slot08`.`test` $$
CREATE PROCEDURE `slot08`.`test` ()
BEGIN
select 1 + max(prio) from categories INTO #my_prio;
select #my_prio;
END $$
DELIMITER ;
Still i do not understand how to use variables in procedures. If I use a DECLARE statement and the variable name miss the # character I got an error from mysql telling me "unknown system variable" - but many examples I saw used this syntax
I mean:
this does not work
CREATE TRIGGER set_prio_default BEFORE INSERT ON categories
FOR EACH ROW
BEGIN
declare my_prio integer default 1;
set my_prio := 1;
SET new.prio := my_prio;
END
If I use # I get syntax error.
Have some hints?
Thanks!
I dont think you have to use the := operator. A simple equals will do. All variables declared inside the stored procedure must be prefixed with the #symbol.
Hey, found the answer. Hope that people with so little experience as me in MySQL procedures could avoid to spend the time I have spent on the same issue. This does work:
DELIMITER $$
CREATE TRIGGER blablabla
BEFORE INSERT ON myStupidTable
FOR EACH ROW
BEGIN
declare my_prio integer;
select 1 + max(prio) from myStupidTable INTO my_prio;
SET new.prio := my_prio;
END $$
DELIMITER ;
It seems that the MySQL syntax errors experienced so far were a delimiter issue.
Greetings
Daniel