postgresql - PostgreSQL : Composite types and select into

标签 postgresql postgresql-9.4 composite-types

有人能解释一下吗? (一切都在下面的例子中!)。我使用 postgresql 9.4。 警告!在下面的代码中,我删除了“object type”复合类型和“example_data”临时表,请确保数据库中没有这些...为了以防万一,我注释了删除命令,如果需要,请取消注释它们。 ..

--drop type if exists object_type;
--drop table if exists example_data;

create type object_type as (
       id text
       ,value text);

create temporary table example_data as (
       select
            'id1'::text as id,
            'example value'::text as value);

do $$
declare
    my_object object_type;
begin

    -- The fiolowing doesn't work, we can't use INTO with the whole object
    -- Some how, it tries to put the whole object into the first attribute:
    select (id,value)::object_type
    into my_object
    from example_data;

    raise warning 'ID: %, VALUE: %', my_object.id, my_object.value;

    -- What a shame! It would have been so much more convenient than the following:    
    -- to feed the object we need to repeat each one of the attribute in the INTO section:
    select id, value
    into  my_object.id, my_object.value
    from example_data;

    raise warning 'ID: %, VALUE: %', my_object.id, my_object.value;

/*
In that example it is not so bad, but when you have very large object, it is very ugly to repeat each one
of the attribute, for example:
select  (att1, att2, att3, att4, att5, att6, att7, att8, att9, att10)::object_type2 into my_object2

and, (very heavy):
select  att1, att2, att3, att4, att5, att6, att7, att8, att9, att10
into my_object2.att1, my_object2.att2, my_object2.att3, my_object2.att4, my_object2.att5, my_object2.att6,
     my_object2.att7, my_object2.att8, my_object2.att9, my_object2.att10

*/

end $$;

--drop type if exists object_type;
--drop table if exists example_data;

最佳答案

已关注 the documentation:

...
select id, value
into my_object
from example_data;
...

关于postgresql - PostgreSQL : Composite types and select into,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39269046/

相关文章:

mysql - 如何使用多个表之间的连接优化sql查询

sql - Postgres 9.4 sql查询超时

postgresql - Postgres 数组列与 JSONB 列

c - 在 PostgreSQL 中,如何根据 C 函数中的类型 Oid 来识别类型是复合类型?

postgresql - SQLAlchemy 复合类型

php - 从超过 1000 万行数据的表中获取记录的最佳方法是什么?

python - 如何从python中的Postsql解释中提取时间成本

sql - PostgreSQL:如何为这种情况编写查询

sql - 列表理解与 PostgreSQL 数组

database - 使用定期传感器数据设计数据库