【问题标题】:Truncating all the tables in a schema in PostgreSQL [duplicate]在PostgreSQL中截断模式中的所有表[重复]
【发布时间】:2015-03-03 19:53:30
【问题描述】:

我正在尝试使用 PostgreSQL 截断模式中的所有表。它显示此错误:

ERROR:  relation "Building" does not exist
CONTEXT:  SQL statement "TRUNCATE TABLE "Building" CASCADE"
PL/pgSQL function truncate_schema(character varying) line 15 at EXECUTE statement

这是我使用的函数:

CREATE OR REPLACE FUNCTION truncate_schema(schema IN VARCHAR) RETURNS void AS $$
DECLARE
    statements CURSOR FOR
        SELECT table_name FROM information_schema.tables
WHERE table_type = 'BASE TABLE' AND table_schema = schema;
BEGIN
    FOR stmt IN statements LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.table_name) || ' CASCADE';
    END LOOP;
END;
$$ LANGUAGE plpgsql;

如何正确地做到这一点?

【问题讨论】:

    标签: function postgresql plpgsql dynamic-sql


    【解决方案1】:

    这可能是因为您没有在 TRUNCATE 语句中包含架构名称,因此它正在寻找 public 架构中的表。

    尝试将TRUNCATE 语句更改为如下内容:

    EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.table_schema) || '.' ||
        quote_ident(stmt.table_name) || ' CASCADE';
    

    另外,关于 CASCADE 需要记住的一点是,它将 TRUNCATE 任何与该表有 外键 关系的表,这可以包括该架构之外的表。

    根据 OP 的评论进行编辑:

    您还需要将table_schema 添加到statements 后面的查询中,以便在EXECUTE 语句中可用。

    【讨论】:

    • 感谢您的回复。它正在制作另一个错误记录“stmt”没有字段“table_schema”。
    【解决方案2】:

    这样试试

    CREATE OR REPLACE FUNCTION truncate_schema(_schema character varying)
      RETURNS void AS
    $BODY$
    declare
        selectrow record;
    begin
    for selectrow in
    select 'TRUNCATE TABLE ' || quote_ident(_schema) || '.' ||quote_ident(t.table_name) || ' CASCADE;' as qry 
    from (
         SELECT table_name 
         FROM information_schema.tables
         WHERE table_type = 'BASE TABLE' AND table_schema = _schema
         )t
    loop
    execute selectrow.qry;
    end loop;
    end;
    $BODY$
      LANGUAGE plpgsql
    

    【讨论】:

    • 太棒了。它有效。非常感谢
    • 你不认为最后一行的末尾需要一个分号..
    • 谢谢,很有帮助!
    猜你喜欢
    • 2011-03-13
    • 2014-04-06
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2013-09-25
    相关资源
    最近更新 更多