我一直在搜索这个站点,以了解如何将 select 语句的结果转储到数组中,这样我就可以遍历数组。但是我还没有幸运地找到一个简单的例子。下面的代码是我所做的一个例子。但是我无法弄清楚如何使用数组来做到这一点。只有一个行结构。每当我尝试将查询结果分配给数组时,我都会收到此子查询错误(即类似于“array := (select...from sometable)”之类的东西,我理解,但必须有办法做到这一点。谢谢(补充:我在这个实际代码下面更喜欢的伪代码)。
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 $$;
希望这可以解决问题。