Construct Dynamic Query Inside MySQL Stored Procedure
by Prabhat Rai

Posted on April 15, 2015 at 12:15 PM


Sometimes we need to construct a query inside a stored procedure. Lets say we have fields like day1, day2, day3…, and we need to fetch day1, for some other case we need to fetch for day2 and so on. Why write different procedures just write a single SP construct the query by passing the day number and then execute the query. Lets see this with an example :


BEGIN
    DECLARE FIELD_FETCH TEXT;
    SET FIELD_FETCH = CONCAT('day',v_day);
    SET @sql = CONCAT('SELECT id,', FIELD_FETCH, ' AS current_day FROM xxx');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END

Explanation :


The first 2 line we declared a field FIELD_FETCH and assigned it with the value “dayN” where N is the parameter v_day passed to SP


Then we construct query using CONCAT function, Then we Prepare SQL statement from the created query, The next line executes the query, then we deallocate the SQL statement.


Lets say we pass 1 as v_day, then our SQL query will be,


SELECT id,day1 As current_day FROM xxx;

If we pass 2 then,


SELECT id,day2 As current_day FROM xxx;

We can use this approach to save our time. Happy Coding. 🙂



Share this

Search

  Recent Tips

See All »

  Recent Posts

  • Creating Installer for Laravel Project

    When you are working on a laravel project there is some basic setup that needs to be done for each install of the project. Like Permissions for ...

  • Laravel Queues With Supervisor

    In this blog, we are going to take a look into Laravel Queues. Queues allow you to defer the processing of a time-consuming task, such as sending a...

  • Partials & Utils in Handlebars

    PARTIALS Let’s say we have a structure like the following : data = { students : [{ name : ‘ABC’, roll : 1 }, { name : ‘DEF&...

See All »

  Recent Seminars

  • PHP 8 - Features

    PHP 8 has been officially released in November 2020! This new major update brings many optimizations and powerful features to the language. This...

  • ProxySQL

    ProxySQL is a high-performance SQL proxy. ProxySQL runs as a daemon watched by a monitoring process. The process monitors the daemon and restarts i...

  • Unix Commands & Shell Scripts to help save our time

    Time is important. We should not waste it doing trivial things. Automate things wherever possible.

See All »