【发布时间】:2021-06-24 15:27:08
【问题描述】:
我正在尝试在 postgresql 中编写函数,该函数创建带有 table_name 文本列的 temp_table,table_rec jsonb 并用我的表中的表名填充它,其中包含 json 中的表和记录的名称。我在字符串中有 for 循环,我想执行它。 但它不起作用。 我有变量 rec 记录、sql_query 文本和 tab_name 文本,我想这样做:
CREATE OR REPLACE FUNCTION public.test51(
)
RETURNS TABLE(tabel_name text, record_json jsonb)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
declare
rec record;
tabel_name text;
tabel_names text[];
counter integer := 1;
sql_query text;
limit_for_sending integer;
rec_count integer;
begin
select into tabel_names array(select "TABLE_NAME" from public."TABLES");
create temp table temp_tab(tab_nam text, recik jsonb);
while array_length(tabel_names, 1) >= counter loop
tabel_name := '"' || tabel_names[counter] || '"';
select into limit_for_sending "TABLE_LIMIT_FOR_SENDING_DATA" from public."TABLES" where "TABLE_NAME" = tabel_name;
sql_query := 'select count(*) from public.' || tabel_name;
execute sql_query into rec_count;
if (rec_count >= limit_for_sending and limit_for_sending is not null) then
sql_query := 'for rec in select * from public.' || tabel_name || '
loop
insert into temp_tab
select ' || tabel_name || ', to_jsonb(rec);
end loop';
execute sql_query;
end if;
counter := counter + 1;
end loop;
return query
select * from temp_tabik;
drop table temp_tabik;
end;
$BODY$;
感谢您的回复。
【问题讨论】:
-
感谢您的回复。我知道 temp_table 没用。该功能不是最终的,我不想创建新表。我对执行变量 sql_script 感到好奇。我知道我可以执行 DDL 和 DML 脚本,但我不知道是否可以以相同的方式执行 for 循环和条件。我现在将更新代码。
-
“但它不起作用......我想这样做:(一些sql代码)”?现在我们需要猜测您想用该代码做什么?尝试将您的问题变成minimal reproducible example。添加示例输入和预期输出。
标签: postgresql for-loop execute control-structure