嘗試:
DELIMITER //
CREATE PROCEDURE `my_sp` (
IN `in_db_name` VARCHAR(32),
OUT `out_result` VARCHAR(32)
)
BEGIN
SET @`query` := CONCAT('SELECT `my_col` INTO @`_out_result`
FROM `', `in_db_name`, '`.`my_table`
WHERE `id` = 1');
PREPARE `stmt` FROM @`query`;
EXECUTE `stmt`;
SET `out_result` := @`_out_result`;
DEALLOCATE PREPARE `stmt`;
END//
DELIMITER ;
見14.5 Prepared SQL Statement Syntax。
例子:
mysql> DROP TABLE IF EXISTS `my_table`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `my_table` (
-> `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-> `my_col` VARCHAR(32) NOT NULL
->);
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO `my_table` (`my_col`)
-> VALUES ('ONE');
Query OK, 1 row affected (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE `my_sp` (
-> IN `in_db_name` VARCHAR(32),
-> OUT `out_result` VARCHAR(32)
->)
-> BEGIN
-> SET @`query` := CONCAT('SELECT `my_col` INTO @`_out_result`
'> FROM `', `in_db_name`, '`.`my_table`
'> WHERE `id` = 1');
-> PREPARE `stmt` FROM @`query`;
-> EXECUTE `stmt`;
-> SET `out_result` := @`_out_result`;
-> DEALLOCATE PREPARE `stmt`;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `my_sp`('test', @`my_out_result`);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @`my_out_result`;
+------------------+
| @`my_out_result` |
+------------------+
| ONE |
+------------------+
1 row in set (0.00 sec)
不能在報表編制更改表名,只有參數值。準備語句是數據庫準備(解釋)預先執行此查詢的計劃的準備工作,並使用此準備好的計劃以不同參數執行查詢。如果更改表名,那麼對於數據庫和數據庫系統來說,這是完全不同的執行計劃,必須重新從頭開始重新計算執行計劃。這不是事先準備的要點。 – sbrbot