如何在PL / pgSQL中使用PostgreSQL INFORMATION_SCHEMA的结果?

时间:2016-10-20 03:08:37

标签: postgresql plpgsql

我正在尝试编写一个查询INFORMATION_SCHEMA的通用存储函数,并使用该信息来访问INFORMATION_SCHEMA描述的表的实际字段值。这是一段代码,显示了我想要做的事情:

select_sql := 'SELECT * FROM "' || tableName || '" WHERE "' || tablePKey || '" = ''' || key_id || ''';';
FOR existing_rec IN EXECUTE select_sql LOOP
    describe_sql := 'SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS
                     WHERE table_name = ''' || tableName || ''';';
    FOR describe_rec IN EXECUTE describe_sql LOOP
        RAISE NOTICE 'table: % field: % value: %', 
                      tableName, 
                      describe_rec.column_name, 
 This is my issue ->  existing_rec."describe_rec.column_name"; <- This is my issue.
    END LOOP;
END LOOP;

如何使用从INFORMATION_SCHEMA中检索到的字段名称从外部循环中获取existing_rec中字段的实际值?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要表格的内容。这不存储在任何变量中,但您可以查询表并将结果存储在新变量中:

-- Add this line:
DECLARE _content RECORD;
....
FOR existing_rec IN EXECUTE select_sql LOOP
    describe_sql := 'SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS
                     WHERE table_name = ''' || tableName || ''';';
    FOR describe_rec IN EXECUTE describe_sql LOOP

        -- Add following statement:
        EXECUTE format('SELECT %I FROM %I',
                         describe_rec.column_name,
                         _table) INTO _content;

        RAISE NOTICE 'table: % field: % value: %', 
                      tableName, 
                      describe_rec.column_name, 
                      _content;
    END LOOP;
END LOOP;