CREATE TABLE IF NOT EXISTS test1(
id int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS test2 LIKE test1;
CREATE TABLE IF NOT EXISTS test3 LIKE test1;
CREATE TABLE IF NOT EXISTS test4 LIKE test1;
-- set table schema and pattern matching for tables
SET @schema = 'testdb';
SET @pattern = 'test%';
接下来,需要构建动态DROP TABLE语句:
-- build dynamic sql (DROP TABLE tbl1, tbl2...;)
SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';')
INTO @droplike
FROM information_schema.tables
WHERE @schema = database()
AND table_name LIKE @pattern;
然后,可以显示动态SQL以验证其是否正常工作:
-- display the dynamic sql statement
SELECT @droplike;
执行上面语句,得到以下结果 -
mysql> SELECT @droplike;
+-----------------------------------------------------------------+
| @droplike |
+-----------------------------------------------------------------+
| DROP TABLE testdb.test1,testdb.test2,testdb.test3,testdb.test4; |
+-----------------------------------------------------------------+
1 row in set