Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Stored Procedure: Boolean Logic in IF THEN

I'm looking for the proper syntax (if this is possible in MySQL stored procedures) for using logical operators in an IF THEN statement. Here's something along the lines of what I would like to do, but I'm not certain if I should type "OR" or "||" in the IF ... THEN clause:

DELIMITER $$

CREATE PROCEDURE `MyStoredProc` (_id INT)
BEGIN

  DECLARE testVal1 INT DEFAULT 0;
  DECLARE testVal2 INT DEFAULT 0;

  SELECT value1, value2 INTO testVal1, testVal2 
    FROM ValueTable 
   WHERE id = _id;

 IF testVal1 > 0 OR testVal2 > 0 THEN

   UPDATE ValueTable 
      SET value1 = (value1+1) 
    WHERE id=_id;

 END IF;

END$$
like image 685
xncroft Avatar asked May 12 '10 18:05

xncroft


People also ask

How do you return a value from a stored procedure in MySQL?

To return a value from stored procedure, you need to use user defined session specific variable. Add @ symbol before variable name.

How do you call a stored procedure with parameters in MySQL?

This procedure accepts id of the customer as IN parameter and returns product name (String), customer name (String) and, price (int) values as OUT parameters from the sales table. To call the procedure with parameters pass @parameter_name as parameters, in these parameters the output values are stored.

Which statement Cannot be used inside stored routines?

Stored routines cannot contain arbitrary SQL statements.


1 Answers

I've just tried your procedure to be sure it works, and it does. Also, you should consider specifying the length of your variable's types, eg. INT(10).

Both the OR and || operators are correct (as stated in the Reference Manual).

like image 199
rekaszeru Avatar answered Nov 03 '22 00:11

rekaszeru