TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Conditionally showing part of a query in MySQL stored procedure

I have a MySQL query that I build in php but want to move into a stored procedure. The entire query is good to move into the sproc, except for one complication: In php, depending on a condition, I add a "HAVING ......" as the last line. Is it possible to do a condition, case, etc. to build a query in a similar way?

For example:

PROCEDURE `GeyMyItems`(
    IN query VARCHAR(100)
    )
  BEGIN
    SELECT * FROM my_table a
    JOIN another_table b ON a.id = b.id
    WHERE my_column = 'this_value'

    IF (query = 'abc')
       HAVING a.my_value = '123';

  END$$

DELIMITER ;

I know the syntax of the IF is probably wrong, but I'm just showing what I'm trying to do. Is there a better way to do this?

The only fall back I can think of is to maybe take care of the HAVING portion in php. Just don't include it at all in the SQL, and when I am building my object/array, I can just filter there in my while loop. But I'd like to see how I can utilize a stored procedure for something like this, if at all?

Upvotes: 0

Views: 934

Answers (2)

olegsv
olegsv

Reputation: 1462

If you're using MySQL 5.0 and later, it's pretty easy.

DELIMITER $$ 

CREATE PROCEDURE `GetMyItems`(
    IN query VARCHAR(100)
    )
  BEGIN
    -- Here you construct your SQL
    SET @s = 'SELECT 1';

    IF query = 'abc' THEN
       SET @s = CONCAT( @s, ',2');
    END IF;

    -- Here you execute it.     
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

  END$$

DELIMITER ;

This was a similar question here.

Upvotes: 2

Dan Bracuk
Dan Bracuk

Reputation: 20804

to your where clause add this:

and 
(
(query = 'abc' and a.my_value ='123')
or query <> 'abc'
)

Upvotes: 0

Related Questions