准备好的语句Mysql

时间:2014-01-10 19:26:23

标签: mysql prepared-statement

我有一个准备好的语句,我想直接执行到MySQL服务器;

USE `testdb`;
SET @t = (
    SELECT GROUP_CONCAT(mytab.TABLE_NAME SEPARATOR ', ') 
    FROM (SELECT * FROM information_schema.TABLES as `m` WHERE table_schema = 'testdb' AND table_name LIKE 'mi_%' LIMIT 0,1) as `mytab`
    );
PREPARE `stmt1` FROM 'DROP TABLE t';
EXECUTE `stmt1` USING @t;
DEALLOCATE PREPARE `stmt1`;

然而,当我执行它时,在EXECUTE行上返回一个错误

  

错误代码:1210。EXECUTE

的参数不正确

如果我做错了,我将不胜感激。

我有mysql版本5.1.68

1 个答案:

答案 0 :(得分:3)

您可以在执行前准备完全静态DDL 来解决您的问题。样品:

表:

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| a              |
| b              |
+----------------+
2 rows in set (0.00 sec)

你的(很少修改过的)SQL:

mysql> SET @t = (SELECT GROUP_CONCAT(mytab.TABLE_NAME SEPARATOR ', ') FROM (SELECT * FROM information_schema.TABLES as `m` WHERE table_schema = 'test'
 AND table_name LIKE 'a%' LIMIT 0,1) as `mytab`);
Query OK, 0 rows affected (0.06 sec)

mysql> select @t;
+------+
| @t   |
+------+
| a    |
+------+
1 row in set (0.00 sec)

现在,DDL:

mysql> set @drop = CONCAT('DROP TABLE ', @t);
Query OK, 0 rows affected (0.00 sec)

mysql> select @drop;
+--------------+
| @drop        |
+--------------+
| DROP TABLE a |
+--------------+
1 row in set (0.00 sec)

最后,准备好了声明:

mysql> PREPARE `stmt1` FROM @drop;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql> EXECUTE `stmt1`;
Query OK, 0 rows affected (0.00 sec)

你会得到:

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| b              |
+----------------+
1 row in set (0.00 sec)

您只能使用一个变量(我已添加@drop以提高可读性)