我需要删除以" my_database.test_table5开头的表格。 。 。 "
我该怎么做?
DROP TABLE *
WHERE tablename IN
(
SEL tablename
FROM dbc.tables
WHERE tablename like '%test_table5%'
AND databasename = 'my_database'
)
答案 0 :(得分:3)
您需要编写并执行一些动态SQL来关闭它,因为您无法动态替换SQL语句中的对象,就像您可以使用字段的值一样。虽然很容易让两者混淆起来。
在您的情况下,一个非常准确的存储过程来执行您想要的操作:
CREATE PROCEDURE your_db.drop_tables(IN tableName VARCHAR(30), IN dbName VARCHAR(30))
BEGIN
--Variable for storing the matching table name inside the cursor loop
DECLARE matchingTable VARCHAR(30);
--Variable for storing the dynamic sql we will execute
DECLARE strSQL VARCHAR(500);
--Build the cursor for matching table names in the database.
DECLARE table_cursor CURSOR FOR
SELECT tablename
FROM dbc.tables
WHERE tablename LIKE '%' || :tableName || '%'
AND databasename = :dbName;
--Open the cursor and loop through results
OPEN table_cursor;
label_cursor_loop:
LOOP
--Catch any errors and get out if there is trouble.
FETCH table_cursor INTO matchingTable;
IF (SQLSTATE = '02000') THEN
LEAVE label_cursor_loop;
END IF;
--Set up the drop table statement
SET strSQL = 'DROP TABLE "' || dbName || '"."' || tableName || '";';
--Execute the drop table statement
CALL DBC.SysExecSQL( sqlStatement );
END LOOP label_cursor_loop;
CLOSE table_cursor;
END;
然后,您只需调用它并传递数据库和搜索术语,例如:
CALL your_db.drop_tables('test_table5', 'my_database')
您也可以选择将搜索术语和数据库硬编码到SQL语句中,但这样更有趣,对吧?
最后,这将不加选择地删除任何与您的搜索字词匹配的表格,因此请谨慎操作。保持安全,只在需要核武选项时使用。另外,我只是在没有执行DROP TABLE sql的情况下对此进行了轻微的测试..所以请注意这一点。
答案 1 :(得分:2)
如果这是一次性任务,而您根本不想手动删除20个表,请让数据库为您编写SQL。
Select 'drop table' ¦¦ databasename ¦¦ '.' ¦¦ tablename ¦¦ ';'
From Dbc.TablesV
Where databasename = 'mydatabase'
And tablename like 'test_table5%' ;
然后复制此查询的结果并执行它。
您会发现,“让数据库编写您的SQL”模式将大大减轻您的任务。
如果这是一个重复的任务,或者是批量完成,那么对程序解决方案毫无疑问。
答案 2 :(得分:2)
基于之前的答案和评论,加上一些实际让它起作用的修复,我想发布一个工作过程:
REPLACE PROCEDURE <your_db>.drop_tables(IN tableName VARCHAR(128), IN dbName VARCHAR(128))
BEGIN
--Variable for storing the matching table name inside the cursor loop
DECLARE matchingTable VARCHAR(128);
--Variable for storing the dynamic sql we will execute
DECLARE strSQL VARCHAR(5000);
--Build the cursor for matching table names in the database.
DECLARE table_cursor CURSOR FOR
SELECT tablename
FROM dbc.TablesV
WHERE tablename LIKE :tableName
AND databasename = :dbName;
--Open the cursor and loop through results
OPEN table_cursor;
label_cursor_loop:
LOOP
--Catch any errors and get out if there is trouble.
FETCH table_cursor INTO matchingTable;
IF (SQLSTATE = '02000') THEN
LEAVE label_cursor_loop;
END IF;
--Set up the drop table statement
SET strSQL = 'DROP TABLE "' || dbName || '"."' || matchingTable || '";';
--Execute the drop table statement
CALL DBC.SysExecSQL( strSQL );
END LOOP label_cursor_loop;
CLOSE table_cursor;
END;