Ser*_*hiy 5 postgresql plpgsql
将一个列表转换为单维数组很容易;
my_array integer[];
my_array := ARRAY(SELECT * FROM single_column_table);
Run Code Online (Sandbox Code Playgroud)
但在我的情况下,我需要将具有多个列的表转换为自定义类型对象的数组;
所以我有自定义类型
TYPE dbfile AS
(fileid integer,
deleted boolean,
name text,
parentid integer,
...
ALTER TYPE dbfile
Run Code Online (Sandbox Code Playgroud)
和数组声明为
my_files dbfile[];
-- how to cast table to array of custom types???
my_files := SELECT * FROM get_files(); -- get_files return SETOF dbfile.
Run Code Online (Sandbox Code Playgroud)
如何将表转换为自定义类型数组?
ARRAY()不起作用,因为它需要单列.
Pav*_*ule 10
你必须使用一个ROW构造函数:
postgres=# SELECT * FROM foo;
??????????????
? a ? b ?
??????????????
? 10 ? Hi ?
? 20 ? Hello ?
??????????????
(2 rows)
postgres=# SELECT ARRAY(SELECT ROW(a,b) FROM foo);
????????????????????????????
? array ?
????????????????????????????
? {"(10,Hi)","(20,Hello)"} ?
????????????????????????????
(1 row)
Run Code Online (Sandbox Code Playgroud)
任何PostgreSQL表都有一个名为记录类型表的虚拟列,其中包含与表的列相关的字段.你可以用它:
postgres=# SELECT ARRAY(SELECT foo FROM foo);
????????????????????????????
? array ?
????????????????????????????
? {"(10,Hi)","(20,Hello)"} ?
????????????????????????????
(1 row)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5527 次 |
| 最近记录: |