是否可以将查询结果连接到postgresql中的变量?
MSSQL中有类似的东西:
DECLARE @Names_tmp NVARCHAR(max);
select @Names_tmp =
COALESCE(@Names_tmp + ' UNION ALL ', '') +
FromTable.Name
from FromTable
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
答案 0 :(得分:2)
我认为没有必要使用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)
答案 1 :(得分:1)
使用STRING_AGG
[SQL Fiddle][1]
查询1 :
select string_agg(name,' UNION ALL ') as res from t
<强> Results 强>:
| res |
|------------------------------------------|
| name_1 UNION ALL name_2 UNION ALL name_3 |