BigQuery批量删除指定前缀表及视图:解决代码执行报错问题
在BigQuery中高效删除指定前缀的表和视图
原思路可行性
你的思路是可行的,报错原因是BigQuery的FOR循环变量是行类型对象,而非直接的字符串,直接使用drop_statement会导致类型转换错误,需要明确提取行中的字符串字段。
修复并支持视图的SQL实现
以下是修正后的代码,同时支持删除指定前缀的表和视图:
begin -- 循环遍历所有符合前缀的表和视图,生成对应删除语句并执行 for drop_row in ( select case table_type when 'BASE TABLE' then concat("drop table if exists `", table_catalog, ".", table_schema, ".", table_name, "`") when 'VIEW' then concat("drop view if exists `", table_catalog, ".", table_schema, ".", table_name, "`") end as drop_string from dev.INFORMATION_SCHEMA.TABLES where table_name like "DATA-100%" ) do execute immediate drop_row.drop_string; end for; end
关键说明
- 通过
TABLE_TYPE字段区分表(BASE TABLE)和视图(VIEW),生成对应的删除语句 - 循环变量
drop_row是行对象,必须通过drop_row.drop_string提取具体的删除语句字符串 - 给表名加上反引号
`,避免表名含特殊字符时出错
更高效的简化写法
如果不需要临时表,可直接在循环中查询目标对象,减少中间步骤:
begin declare drop_stmt string; declare cur cursor for select case table_type when 'BASE TABLE' then concat("drop table if exists `", table_catalog, ".", table_schema, ".", table_name, "`") when 'VIEW' then concat("drop view if exists `", table_catalog, ".", table_schema, ".", table_name, "`") end from dev.INFORMATION_SCHEMA.TABLES where table_name like "DATA-100%"; open cur; loop fetch cur into drop_stmt; if done then leave; end if; execute immediate drop_stmt; end loop; close cur; end
内容的提问来源于stack exchange,提问作者philMarius
相关产品推荐
相关产品推荐

