mysql存储过程中执行动态sql
时间: 2024-01-01 20:22:40 浏览: 156
MySQL 存储过程中执行动态SQL语句的方法
5星 · 资源好评率100%
以下是在MySQL存储过程中执行动态SQL的示例:
```sql
-- 示例1:动态SQL拼接和执行
DELIMITER //
CREATE PROCEDURE dynamicSQLExample()
BEGIN
DECLARE selectSql VARCHAR(1000);
DECLARE whereCondition VARCHAR(500);
DECLARE orderByCondition VARCHAR(200);
DECLARE finalSql VARCHAR(2000);
SET selectSql = 'SELECT * FROM your_table';
SET whereCondition = ' WHERE condition_column = value';
SET orderByCondition = ' ORDER BY column_name';
SET @sql = CONCAT(selectSql, whereCondition, orderByCondition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
-- 示例2:动态SQL拼接和执行带参数
DELIMITER //
CREATE PROCEDURE dynamicSQLWithParams(IN conditionValue INT)
BEGIN
DECLARE selectSql VARCHAR(1000);
DECLARE whereCondition VARCHAR(500);
DECLARE finalSql VARCHAR(2000);
SET selectSql = 'SELECT * FROM your_table';
SET whereCondition = CONCAT(' WHERE condition_column = ', conditionValue);
SET @sql = CONCAT(selectSql, whereCondition);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
```
阅读全文