PL / pgSQL函数中的动态SELECT INTO

Kar*_*hik 5 postgresql dynamic-sql plpgsql variable-assignment stored-functions

如何SELECT INTO在Postgres的PL / pgSQL函数内编写动态查询?

假设我有一个名为的变量tb_name,它填充在的FOR循环中information_schema.tables。现在,我有一个名为的变量tc,它将获取每个表的行数。我想要以下内容:

FOR tb_name in select table_name from information_schema.tables where table_schema='some_schema' and table_name like '%1%'
LOOP
EXECUTE FORMAT('select count(*) into' || tc 'from' || tb_name);
END LOOP
Run Code Online (Sandbox Code Playgroud)

应该是什么数据类型tb_name,并tc在这种情况下?

Erw*_*ter 5

CREATE OR REPLACE FUNCTION myfunc(_tbl_pattern text, _schema text = 'public')
  RETURNS void AS  -- or whatever you want to return
$func$
DECLARE
   _tb_name information_schema.tables.table_name%TYPE;  -- currently varchar
   _tc      bigint;  -- count() returns bigint
BEGIN
   FOR _tb_name IN
      SELECT table_name
      FROM   information_schema.tables
      WHERE  table_schema = _schema
      AND    table_name   ~ _tbl_pattern  -- see below!
   LOOP
      EXECUTE format('SELECT count(*) FROM %I.%I', _schema, _tb_name)
      INTO _tc;      

      -- do something with _tc
   END LOOP;
END
$func$  LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)

笔记


解决您的评论:要传递,请使用以下USING子句:

EXECUTE format('SELECT count(*) FROM %I.%I
                WHERE some_column = $1', _schema, _tb_name,column_name)
USING user_def_variable;
Run Code Online (Sandbox Code Playgroud)

有关: