将选择查询的输出存储在 postgres 的一个数组中
我的代码是:
SELECT column_name
FROM information.SCHEMA.columns
WHERE table_name = 'aean'
它返回表aean
的列名称。
现在我已经声明了一个数组:
DECLARE colnames text[]
如何将 select 的输出存储在 colnames 数组中。
是否需要初始化colnames?
My code is:
SELECT column_name
FROM information.SCHEMA.columns
WHERE table_name = 'aean'
It returns column names of table aean
.
Now I have declared an array:
DECLARE colnames text[]
How can I store select's output in colnames array.
Is there any need to initialize colnames?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有两种方法。一种是聚合:
另一种是使用数组构造函数:
我假设这是针对 plpgsql 的。在这种情况下,您可以这样分配它:
There are two ways. One is to aggregate:
The other is to use an array constructor:
I'm presuming this is for plpgsql. In that case you can assign it like this:
我有完全相同的问题。只需对 Denis 给出的解决方案进行另一项工作修改即可(必须指定类型):
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
常规:
使用
ARRAY_AGG
:Regular:
Using
ARRAY_AGG
:转换为数据类型“TEXT”将确保您的查询运行没有任何问题。
在plpgsql中,当我们分配给数组变量时,我们不需要使用类型转换。我的要求是获取特定表的所有列名称的 CSV。我在 plpgsql 中使用了以下代码。
Casting to the datatype "TEXT" will ensure that your queries will run without any problem.
In plpgsql when we assign to a array variable, we need not use the type casting. My requirement was to get a CSV of all the column names of a particular table. I'd used the following code in plpgsql.
检查该列是否存在。
关键点:
如果存在(select _colname = any(colnames))
我们还可以使用
string_agg
String_agg 用法:
check if the column exists or not.
Key point:
if exists(select _colname = any(colnames))
We can also using
string_agg
String_agg usage:
在函数中声明 colnames text[] 数组,然后在 begin 中编写以下查询:
SELECT column_name into colname
FROM信息.SCHEMA.列
WHERE 表名 = 'aean'
declare colnames text[] array in function and then write following query in begin:
SELECT column_name into colnames
FROM information.SCHEMA.columns
WHERE table_name = 'aean'