简体   繁体   中英

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?

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 .

to your where clause add this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM