PostgreSQL动态查询结果的每个元素如何执行一段代码?
How to execute a piece of code for each element of the result of a dynamic query in PostgreSQL?
我的 PostgreSQL 函数中有一个动态查询:
execute format('select something from %', table_name)
我想运行为上述语句返回的每条记录编写一些代码。
我该怎么做?
我的第一个想法如下。
我需要做这样的事情:
execute format('select something from %', table_name)
into my_data;
for my_record in my_data
loop
-- Do something with my_record
end loop;
为了在函数或过程中使用上面的代码,我需要声明变量my_data
和my_record
。
my_record
具有数据类型 record
。 my_data
的数据类型可能是什么?
您可以在 FOR
循环中使用动态语句:
DECLARE
r record;
BEGIN
FOR r IN
EXECUTE format('select something from %I', table_name)
LOOP
/* "r" now contains a table row */
END LOOP;
END;
我的 PostgreSQL 函数中有一个动态查询:
execute format('select something from %', table_name)
我想运行为上述语句返回的每条记录编写一些代码。
我该怎么做?
我的第一个想法如下。
我需要做这样的事情:
execute format('select something from %', table_name)
into my_data;
for my_record in my_data
loop
-- Do something with my_record
end loop;
为了在函数或过程中使用上面的代码,我需要声明变量my_data
和my_record
。
my_record
具有数据类型 record
。 my_data
的数据类型可能是什么?
您可以在 FOR
循环中使用动态语句:
DECLARE
r record;
BEGIN
FOR r IN
EXECUTE format('select something from %I', table_name)
LOOP
/* "r" now contains a table row */
END LOOP;
END;