0

I'm trying to create a stored procedure in MySQL with an if-elseif statement but it doesn't seem to work. I can create a procedure that will run either the if or the elseif but not with the actual switch.

CREATE DEFINER=`root`@`%` PROCEDURE `sp_do_something`(
IN setting VARCHAR(30),
IN setting2 VARCHAR(30),
IN if_else_switch VARCHAR(20))

DETERMINISTIC
IF @if_else_switch = 'foo' then
BEGIN 
...
END;
elseif @if_else_switch = 'bar' then
BEGIN
...
END; 
END IF; 

Then I call it with

CALL `database`.`sp_do_something`('setting', 'setting2', 'foo');

It completes without any errors but just returns "Affected rows: 0" and doesn't appear to be doing any of the actual SQL-code.

I'm guessing that it has something to do with the last value of the call-query and it somehow not being caught by either if - but why?

1 Answer 1

3

Try This

CREATE DEFINER=`root`@`%` PROCEDURE `sp_do_something`(
IN setting VARCHAR(30),
IN setting2 VARCHAR(30),
IN if_else_switch VARCHAR(20))

DETERMINISTIC
IF if_else_switch = 'foo' then
......
elseif if_else_switch = 'bar' then
.......
END IF; 

when you use @ with variable so it is global variable and it value persist till end of the session. and in your case if_else_switch is come parameter so it is local variable. so use the local variable instead global variable

for more know http://www.java2s.com/Tutorial/MySQL/0201__Procedure-Function/LOCALSESSIONANDGLOBALVARIABLESINMYSQL.htm

Sign up to request clarification or add additional context in comments.

1 Comment

That was the issue. Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.