如何解决如何在for循环内实现执行命令-Postgres,dbeaver
我是Postgres的新手。我需要创建一个函数,该函数将获取数据库中所有表的列表,其名称存储在一个表中,然后删除所有早于x天且具有特定row_status的表的记录。某些表没有row_status列。 尝试在dbeaver中保存书面函数时出现错误-> 错误:“ ||”
或附近的语法错误create function delete_old_records1(day1 int,row_status1 character default null,row_status2 character default null)
returns void
language plpgsql
as $$
declare
c all_tables1%rowtype;
begin
for c in select * from all_tables1 loop
if exists(SELECT column_name FROM information_schema.columns
WHERE table_schema = 'yard_kondor' AND table_name =c.table_name AND column_name = 'row_status') then
execute 'delete from '||c.table_name||' where row_create_datetime>current_date-day1+1 and
row_status in (coalesce(row_status1,''P''),row_status2)';
else
execute 'delete from '||c.table_name||' where row_create_datetime>current_date-day1+1';
raise notice 'Table '||c.table_name||' does not have row_status column';
end if;
end loop;
return;
commit;
end;
$$
解决方法
您当前的问题是这一行:
raise notice 'Table '||c.table_name||' does not have row_status column';
那个should be:
raise notice 'Table % does not have row_status column',c.table_name;
但是,您的功能可能会有所改善。通常,强烈建议使用format()
生成动态SQL以正确处理标识符。您也无法commit
使用函数。如果确实需要,请使用一个过程。
create function delete_old_records1(day1 int,row_status1 character default null,row_status2 character default null)
returns void
language plpgsql
as $$
declare
c all_tables1%rowtype;
begin
for c in select * from all_tables1
loop
if exists (SELECT column_name FROM information_schema.columns
WHERE table_schema = 'yard_kondor'
AND table_name = c.table_name
AND column_name = 'row_status') then
execute format('delete from %I
where row_create_datetime > current_date - day1 + 1
and row_status in (coalesce(row_status1,%L),row_status2)',c.table_name,'P');
else
execute format('delete from %I where row_create_datetime > current_date - day1 + 1',c.table_name);
raise notice 'Table % does not have row_status column',c.table_name;
end if;
end loop;
return;
-- you can't commit in a function
end;
$$
,
谢谢您的回答。现在我可以保存函数了,但是目前我在运行函数时遇到问题。
我使用以下功能启动该功能
:DO $$ BEGIN
PERFORM "delete_old_records1"(31,'P','N');
END $$;
我使用ALT + X启动脚本(也尝试过select delete_old_records1(31,'N');
),并遇到此错误:
SQL错误[42703]:错误:列“ day1”不存在 其中:PL / pgSQL函数delete_old_records1(integer,character,character)第11行位于EXECUTE语句 SQL语句“ SELECT“ delete_old_records1”(31,'P','N')“ PL / pgSQL函数inline_code_block在PERFORM的第2行
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。