Dynamic SQL Query Generation Using Stored Procedures in MySQL

Dynamic SQL allows you to construct and execute SQL statements at runtime. In MySQL, this can be achieved using stored procedures combined with the PREPARE and EXECUTE commands. This tutorial provides step-by-step instructions and examples for implementing dynamic SQL in MySQL.


1. Why Use Dynamic SQL?

Dynamic SQL is useful when:

You need to execute queries with dynamically changing conditions.

Query structures depend on user input.

Building flexible reports or handling variable table or column names.


2. Setting Up the Environment

Create a sample database and table:

CREATE DATABASE dynamic_sql_demo;

USE dynamic_sql_demo;


CREATE TABLE employees (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100),

    department_id INT,

    salary DECIMAL(10, 2),

    hire_date DATE

);


INSERT INTO employees (name, department_id, salary, hire_date)

VALUES

    ('Alice', 1, 5000, '2022-01-15'),

    ('Bob', 1, 5500, '2022-05-20'),

    ('Charlie', 2, 6000, '2023-03-10'),

    ('Diana', 2, 6500, '2023-08-01'),

    ('Eve', 3, 7000, '2023-12-05');


3. Syntax for Dynamic SQL in MySQL

Dynamic SQL in MySQL involves the following steps:

Construct the SQL query as a string.

Use PREPARE to prepare the query.

Use EXECUTE to run the query.

Optionally, use DEALLOCATE PREPARE to free memory.


4. Writing a Basic Stored Procedure with Dynamic SQL

Example 1: Dynamic Filtering


Create a stored procedure to filter employees based on dynamic conditions:

DELIMITER //


CREATE PROCEDURE GetEmployees(IN filter_condition VARCHAR(255))

BEGIN

    SET @sql = CONCAT('SELECT * FROM employees WHERE ', filter_condition);


    PREPARE stmt FROM @sql;

    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;

END //


DELIMITER ;


Call the procedure:

CALL GetEmployees('salary > 6000');

Output:

| id | name   | department_id | salary | hire_date  |

|----|--------|---------------|--------|------------|

|  5 | Eve    |             3 |  7000  | 2023-12-05 |


5. Advanced Examples

Example 2: Dynamic Column Selection


Create a procedure to select specific columns dynamically:

DELIMITER //


CREATE PROCEDURE SelectColumns(IN columns VARCHAR(255))

BEGIN

    SET @sql = CONCAT('SELECT ', columns, ' FROM employees');


    PREPARE stmt FROM @sql;

    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;

END //


DELIMITER ;


Call the procedure:

CALL SelectColumns('name, salary');

Output:

| name     | salary |

|----------|--------|

| Alice    | 5000   |

| Bob      | 5500   |

| Charlie  | 6000   |

| Diana    | 6500   |

| Eve      | 7000   |


Example 3: Handling Table Names Dynamically


Create a procedure to query a dynamic table name:

DELIMITER //


CREATE PROCEDURE QueryTable(IN table_name VARCHAR(255))

BEGIN

    SET @sql = CONCAT('SELECT * FROM ', table_name);


    PREPARE stmt FROM @sql;

    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;

END //


DELIMITER ;


Call the procedure:

CALL QueryTable('employees');


Example 4: Combining Dynamic SQL with Parameters


Create a procedure with both dynamic SQL and user input:

DELIMITER //


CREATE PROCEDURE FilteredEmployees(

    IN filter_condition VARCHAR(255),

    IN limit_rows INT

)

BEGIN

    SET @sql = CONCAT('SELECT * FROM employees WHERE ', filter_condition, ' LIMIT ', limit_rows);


    PREPARE stmt FROM @sql;

    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;

END //


DELIMITER ;


Call the procedure:

CALL FilteredEmployees('salary > 5000', 3);


6. Best Practices for Dynamic SQL

Validate Input: Ensure that dynamic parts of the SQL are sanitized to prevent SQL injection attacks.

Use strict validation or predefined options for input.

Debugging: Log or print the dynamic SQL string for debugging before execution.

SELECT @sql; -- Use this before EXECUTE.

Avoid Overuse: Use dynamic SQL only when absolutely necessary; static SQL is easier to debug and optimize.


7. Troubleshooting Tips

If queries fail, check the dynamic SQL string:

SELECT @sql;

Ensure proper formatting of the SQL statement.

Use LIMIT to avoid overly large result sets during testing.

By following this guide, you can effectively use stored procedures to generate and execute dynamic SQL in MySQL, making your applications more flexible and powerful.  Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.

Comments

Popular posts from this blog

Integrating PHP with Message Queues RabbitMQ Kafka

FastAPI and UVLoop: The Perfect Pair for Asynchronous API Development

Konfigurasi dan Instalasi PostgreSQL Secara Lengkap di Windows Linux dan MacOS