将查询结果连接到 PostgreSQL 中的变量中
Concatenate the result of a query into a variable in PostgreSQL
是否可以将查询结果连接到 postgresql 中的变量中?
在 MSSQL 中是这样的:
DECLARE @Names_tmp NVARCHAR(max);
select @Names_tmp =
COALESCE(@Names_tmp + ' UNION ALL ', '') +
FromTable.Name
from FromTable
来自表结构:
Key Name Other Columns ...
1 name_1 asd
2 name_2 asd
3 name_3 asd
PRINT CAST(@Names_tmp AS NTEXT)
结果:
name_1 UNION ALL name_2 UNION ALL name 3
我觉得没必要用 plpgsql
来解决这个问题。 PostgreSQL aggregate functions 应该这样做:
CREATE TEMPORARY TABLE t (id INT, name TEXT, asd TEXT);
INSERT INTO t VALUES (1,'name_1','asd'),
(2,'name_2','asd'),
(3,'name_3','asd');
SELECT ARRAY_TO_STRING(ARRAY_AGG(name),' UNION ALL ') FROM t;
SELECT STRING_AGG(name, ' UNION ALL ') FROM t;
结果:
------------------------------------------
name_1 UNION ALL name_2 UNION ALL name_3
(1 Zeile)
使用STRING_AGG
[SQL Fiddle][1]
查询 1:
select string_agg(name,' UNION ALL ') as res from t
| res |
|------------------------------------------|
| name_1 UNION ALL name_2 UNION ALL name_3 |
是否可以将查询结果连接到 postgresql 中的变量中?
在 MSSQL 中是这样的:
DECLARE @Names_tmp NVARCHAR(max);
select @Names_tmp =
COALESCE(@Names_tmp + ' UNION ALL ', '') +
FromTable.Name
from FromTable
来自表结构:
Key Name Other Columns ...
1 name_1 asd
2 name_2 asd
3 name_3 asd
PRINT CAST(@Names_tmp AS NTEXT)
结果:
name_1 UNION ALL name_2 UNION ALL name 3
我觉得没必要用 plpgsql
来解决这个问题。 PostgreSQL aggregate functions 应该这样做:
CREATE TEMPORARY TABLE t (id INT, name TEXT, asd TEXT);
INSERT INTO t VALUES (1,'name_1','asd'),
(2,'name_2','asd'),
(3,'name_3','asd');
SELECT ARRAY_TO_STRING(ARRAY_AGG(name),' UNION ALL ') FROM t;
SELECT STRING_AGG(name, ' UNION ALL ') FROM t;
结果:
------------------------------------------
name_1 UNION ALL name_2 UNION ALL name_3
(1 Zeile)
使用STRING_AGG
[SQL Fiddle][1]
查询 1:
select string_agg(name,' UNION ALL ') as res from t
| res |
|------------------------------------------|
| name_1 UNION ALL name_2 UNION ALL name_3 |