繁体   English   中英

BigQuery:遍历数据集中的表并删除具有特定前缀的表

[英]BigQuery: Loop through tables in dataset and drop tables with a specific prefix

我们在 BigQuery 中的开发环境与开发数据集隔离,即 BigQuery 中的dev 环境通过每个表的票证前缀进一步隔离,即DATA-100-change-table将对应于 DATA-100 票证。

我知道为 BigQuery 设置 TTL ,但是,我也对可以手动运行以删除表的查询感兴趣。

到目前为止,我有以下内容:

begin
  -- Create temporary table of tables to drop from `dev` with prefix
  create temp table to_drop (drop_string STRING)
  as
  (
    select concat("drop table if exists ", table_catalog, ".", table_schema, ".", table_name)
    from dev.INFORMATION_SCHEMA.TABLES
    where table_name like "DATA-100%"
  );

  -- Loop through table and execute drop_string statements
  for drop_statement in (select drop_string from to_drop)
  do
    execute immediate drop_statement;
  end for;
end

但是,这失败并出现以下错误:

Query error: Cannot coerce expression drop_statement to type STRING at [14:23]

我的方法就在这里吗? 如何最好地删除 BigQuery 中带有前缀的所有表?

另外,如果可能的话,我希望这个查询也能处理视图。

for 循环中的变量 drop_statement 包含一个结构。 所以你必须使用drop_statement.drop_string访问字符串。

begin
  -- Create temporary table of tables to drop from `dev` with prefix
  create temp table to_drop (drop_string STRING)
  as
  (
    select concat("drop table if exists ", table_catalog, ".", table_schema, ".", table_name)
    from dev.INFORMATION_SCHEMA.TABLES
    where table_name like "DATA-100%" and table_type = 'BASE TABLE'
  );

  -- Loop through table and execute drop_string statements
  for drop_statement in (select drop_string from to_drop)
  do
    execute immediate drop_statement.drop_string;
  end for;
end

要删除视图,只需将table_type = "BASE TABLE"替换为table_type = "VIEW"并使用drop view if exists )。

p13rr0m 的回答为灵感,我得出了以下结论:

begin
  create temp table to_drop (drop_string STRING)
  as 
  (
    select
      case 
        when table_type = "BASE TABLE" then concat("drop table if exists `", table_catalog, ".", table_schema, ".", table_name, "`")
        when table_type = "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%"
  );

  for drop_statement in (select drop_string from to_drop)
  do
    execute immediate drop_statement.drop_string;
  end for;
end

不得不在表中添加反引号,因为它无法删除视图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM