postgresql PSQL中插入行的计数器

ds97pgxw  于 2022-12-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(128)

我正在寻找一个PostgreSQL的等价物下图。我有一个脚本批插入多个表,想法是声明一些变量计数有多少每个已插入时执行。

到目前为止,我已经有了这个,但是对于@@ROW_COUNT还没有直接的方法:

BEGIN TRANSACTION;
DO $$ 
DECLARE
   EmailModulesTotal            integer := 0;
   DependenciesTotal            integer := 0;
   ModuleTypesTotal             integer := 0;
   ModuleSectionsTotal          integer := 0;
BEGIN

-- inserts go here

  RAISE NOTICE 'Total Inserted/Updated Email Modules: %
  Total Inserted Dependencies: %
  Total Inserted Module Types: %
  Total Inserted Module Sections: %',
    EmailModulesTotal, 
    DependenciesTotal, 
    ModuleTypesTotal, 
    ModuleSectionsTotal
END $$;
COMMIT TRANSACTION;
h43kikqp

h43kikqp1#

在PL/pgSQL中,您可以使用get diagnostics访问受影响(即插入到您的用例中)的行数。

create temporary table t (id serial, txt text);

do language plpgsql
$$
declare
    counter integer;
begin
    insert into t(txt) values ('One'), ('Two'), ('Three');
    get diagnostics counter = row_count;
    raise notice 'Inserted % rows', counter;
end;
$$;

结果为Inserted 3 rows
普通SQL中的另一种方法是使用数据修改CTE:

with cte as
(
 insert into t(txt) values ('One'), ('Two'), ('Three')
 returning 1
)
select count(*) from cte;

哪个更适合你。

相关问题