表t2
有2列(id,表名),其值分别为(1,2,3)x(toto,titi,tata):
id|tablename|
1 |toto|
2 |tata|
3 |titi|
我想创建一个将id作为用户变量输入的过程,并执行以下操作:
BEGIN
CREATE TABLE `newtable` AS (
SELECT * FROM (SELECT tablename from t2 WHERE id=2);
);
END
结果应表现为查询为:
BEGIN
CREATE TABLE `newtable` AS (
SELECT * FROM `tata`
);
END
答案 0 :(得分:1)
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `pr_create_table_by_reference`(
IN `str_new_table_name` VARCHAR(50),
IN `int_id` INT
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE STR_TABLE_NAME VARCHAR(1000) DEFAULT NULL;
SELECT tablename INTO STR_TABLE_NAME FROM t2 WHERE id = int_id LIMIT 1;
SET @prep_stmt = CONCAT('CREATE TABLE ', str_new_table_name ,' as ( SELECT * FROM ', STR_TABLE_NAME , ')');
PREPARE stmt FROM @prep_stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
$$
程序调用:
SET @new_table:= 'newTable';
SET @id:= 2;
CALL `pr_create_table_by_reference`(@new_table, @id);
OR
CALL `pr_create_table_by_reference`('newTable', 2);