我一直在搜索这个网站,以了解如何将select语句的结果转储到数组中,因此我可以遍历数组。但是我没有幸运地找到一个简单的例子。下面的代码是我所做的一个例子。但是,我无法弄清楚如何使用数组执行此操作。只有一行构造。每当我尝试将查询结果分配给数组时,我都会得到这个子查询错误(例如“array:=(select from from sometable)”,我理解,但必须有一种方法可以做到这一点。谢谢事先。(补充:PSeudo-Code,我更喜欢这个实际代码)。
DO
$$
DECLARE
nRowCount bigint;
i record;
BEGIN
DROP TABLE IF EXISTS companies_sample_db_temp;
CREATE TABLE companies_sample_db_temp (
col1 varchar
, col2 varchar
, col3 varchar
);
INSERT INTO companies_sample_db_temp VALUES ('McDonalds','Los Angeles','CA');
INSERT INTO companies_sample_db_temp VALUES ('Starbucks','Seattle','WA');
INSERT INTO companies_sample_db_temp VALUES ('Oracle','San Francisco','CA');
-- SELECT * FROM companies_sample_db_temp;
FOR i IN
with a as
(
SELECT
ARRAY[col1::text
, col2::text
, col3::text
] as coltext
FROM companies_sample_db_temp AS my_arr
)
select row_number() over(), coltext from a
LOOP
-- RAISE INFO 'nRowCount: %', nRowCount;
RAISE INFO 'Array Info: %', i.coltext[1];
END LOOP;
END
$$;
/*********** Pseudo Code of what I'd rather do *******************/
DO
$$
DECLARE
-- Assign results of this query to an array
my_arr := SELECT col1, col2,col3 FROM companies_sample_db_temp;
i record;
BEGIN
-- Loop through an "array" not a table using a select statement.
FOR i IN
-- Iterate through each row of the array
my_arr[i] -- Row from the select query
LOOP
-- Display an elements within a single array row
RAISE INFO 'Array Info: %', my_arr[i][1]; -- col1
RAISE INFO 'Array Info: %', my_arr[i][2]; -- col2
RAISE INFO 'Array Info: %', my_arr[i][3]; -- col3
END LOOP;
END $$;
希望这能解决问题。
答案 0 :(得分:1)
鉴于您尝试此操作的原因是“性能”,请考虑以下事项: