截断函数在 postgres 中不起作用

truncate function doesnt work in postgres

我创建了以下函数来处理 运行 以 "irm_gtresult" 开头的一堆表格。我的函数中没有语法错误,但是当我 运行 它时,该函数不会 t运行 分类表。这里可能有什么问题?

我的 Postgres 数据库版本是 8.4。

create or replace function br()
RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
row text;
BEGIN
 FOR row IN
select table_name from information_schema.tables where table_name ILIKE 'irm_gtresult%'
LOOP
EXECUTE 'TRUNCATE TABLE ' || row;
END LOOP;
END;
$$;

致电:

select br();

您的代码有效。我测试过它在 Postgres 9.4 中对我有用。
使用 outdated and unsupported version 8.4(如您添加的那样)可能 是问题所在。版本太旧,考虑升级到当前版本。

不过,我有几个建议:

  • 不要使用关键字 row 作为变量名。
  • 您不需要循环,您可以在一个命令中 TRUNCATE 所有表。更快,更短。
  • 如果有依赖关系,您可能需要添加CASCADE。注意效果。

CREATE OR REPLACE FUNCTION br()
  RETURNS void AS
$func$
BEGIN
   EXECUTE (
      SELECT 'TRUNCATE TABLE '
          || string_agg(format('%I.%I', schemaname, tablename), ',')
          || ' CASCADE'
      FROM   pg_tables t
      WHERE  tablename ILIKE 'irm_gtresult%'
      AND    schemaname = 'public'
      -- AND tableowner = 'postgres'  -- optionaly restrict to one user
      );
END
$func$  LANGUAGE plpgsql;

致电:

SELECT br();

我正在像您一样使用视图 pg_tables from the system catalog. You can as well use information_schema.tables。注意细微差别:

  • How to check if a table exists in a given schema

更多解释的相关答案:

  • Can I truncate tables dynamically?
  • Truncating all tables in a Postgres database