16

The objective is to alter a query string within a Mysql stored procedure based on input variables.

Something like this:

CREATE DEFINER=`root`@`localhost` PROCEDURE `func`(type VARCHAR(15))
BEGIN
    SET @type = type;

    -- Check for the sort parameter
    if @type="asc" THEN
        SET @sort = " order by name asc";
    elseif @type="desc" THEN
        SET @sort = " order by name desc";
    else
        SET @sort ="";
    end if;

SELECT id, name from table @sort;

END    
4
  • 1
    The solution is to use execute, and concat: CREATE DEFINER=root@localhost PROCEDURE test(input VARCHAR(15)) BEGIN SET @input = input; if @input="asc" then SET @sort = " order by ActivityLogKey asc"; elseif @input = "desc" then SET @sort = " order by ActivityLogKey desc"; else SET @sort =""; end if; SET @query = CONCAT('select * from activitylog ',@sort,' limit 0, 5'); PREPARE stmt FROM @query; EXECUTE stmt; DEALLOCATE PREPARE stmt; END Commented Dec 18, 2011 at 3:57
  • If this is the solution why you didn't add it as an answer and accept it or edit your question with it. Commented Dec 18, 2011 at 11:51
  • 1
    Without 100 reputation, I have to wait 8 hours to answer my own question Commented Dec 18, 2011 at 17:10
  • @BenGuthrie: Then wait. The limitation wasn't put into place because the devs want you to post your answer in the wrong location; it was put into place because they want you to wait. There are reasons for this. Commented Dec 18, 2011 at 17:13

1 Answer 1

25

The solution is to use execute, and concat:

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`(input VARCHAR(15))
BEGIN
SET @input = input;

if @input="asc" then
    SET @sort = " order by ActivityLogKey asc";
elseif @input = "desc" then
    SET @sort = " order by ActivityLogKey desc";
else
    SET @sort ="";
end if;

SET @query = CONCAT('select * from activitylog ',@sort,' limit 0, 5');

PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

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

2 Comments

The usefulness I found for this is to be able to conditionally insert joins, fields, or any other other SQL code as part of the stored proc rather than in PHP. It seems far cleaner to implement this at the stored proc level.
BTW, execute and concat are solution even if not defining a stored procedure; good example under "But if you don't change... implement a prepared statement to generate dynamic SQL." in Taryn's answer here. I find this useful for "throwaway" (one-time) queries.

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.