ข้ามไปยังเนื้อหาหลัก

MySQL EXECUTE Statements

The `EXECUTE` statement in MySQL is used to run a previously prepared SQL statement. It is particularly useful for executing dynamic or parameterized queries that have been prepared using the `PREPARE` statement.

Usage

The `EXECUTE` statement is employed when executing a prepared SQL statement, especially with varying input parameters. It follows a `PREPARE` statement and optionally uses `USING` to pass parameters.

sql
EXECUTE stmt_name [USING @var1, @var2, ...];

In this syntax, `stmt_name` is the identifier of the prepared statement, and the optional `USING` clause allows the passing of variables as parameters.

Examples

1. Basic Execution

sql
PREPARE stmt FROM 'SELECT * FROM employees WHERE department_id = ?';
SET @dept_id = 5;
EXECUTE stmt USING @dept_id;

In this example, a basic prepared statement is executed to select employees from a specific department.

2. Execution with Multiple Parameters

sql
PREPARE stmt FROM 'SELECT * FROM employees WHERE department_id = ? AND salary > ?';
SET @dept_id = 5, @min_salary = 50000;
EXECUTE stmt USING @dept_id, @min_salary;

This example executes a prepared statement that filters employees by department and minimum salary using two parameters.

3. Dynamic Table Name

sql
SET @table_name = 'employees';
SET @query = CONCAT('SELECT * FROM ', @table_name, ' WHERE department_id = ?');
PREPARE stmt FROM @query;
SET @dept_id = 5;
EXECUTE stmt USING @dept_id;

Here, a dynamic query is constructed with a table name specified at runtime, demonstrating usage of `EXECUTE` with dynamic SQL.

Tips and Best Practices

  • Use with `PREPARE`. Always use `EXECUTE` in conjunction with `PREPARE` for parameterized queries.
  • Sanitize Inputs. Ensure parameters passed to `EXECUTE` are sanitized to prevent SQL injection.
  • Leverage Caching. Reuse prepared statements to benefit from performance improvements due to query plan caching.
  • Close Statements. Use `DEALLOCATE PREPARE` to release resources once a prepared statement is no longer needed.
  • Understand Scope. Prepared statements are limited to the session in which they are created. Plan accordingly when using them in applications or stored procedures.
  • Control Dynamic Inputs. When using dynamic table names, validate and control inputs to prevent SQL injection vulnerabilities.