错误:关系列“data_type”不存在

时间:2017-01-28 17:11:59

标签: postgresql plpgsql

我正在尝试使用触发器从表中返回列的'data_type'。 SQL FIDDLE有完整的触发器......但是比特是:

 FOR each_column IN
        SELECT
            attname as column_name,
            format_type(atttypid, atttypmod) AS data_type
        FROM
            pg_attribute
        WHERE
            attrelid =
            (
                SELECT
                    oid
                FROM
                    pg_class
                WHERE
                    relname = tg_relname
           LIMIT 1 )
        AND attnum > 0
    LOOP

我得到的错误(在此查询结束时):

ERROR: column "data_type" of relation does not exist Where: PL/pgSQL function log.insert_history() line 94 at SQL statement

我不确定我错过了什么...有没有人看到它?

2 个答案:

答案 0 :(得分:1)

您可以使用下面的SQL获取表YOUR_SCHEMA.YOUR_TABLE_NAME中的所有列:

SELECT
    a.attname, LOWER(format_type(a.atttypid, a.atttypmod)) AS type, d.adsrc, 
    a.attnotnull, a.atthasdef
FROM
    pg_attribute a 
        LEFT JOIN pg_attrdef d ON (a.attrelid = d.adrelid AND a.attnum = d.adnum)
WHERE 
    a.attnum > 0 AND NOT a.attisdropped
    AND a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname = 'YOUR_TABLE_NAME'
        AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = 'YOUR_SCHEMA'))
ORDER BY 
    a.attnum;

答案 1 :(得分:0)

@Abelisto是正确的 - 我忘了在'创建表格中添加声明'。糟糕!

SQL FIDDLE is HERE中的工作解决方案。