PL / pgSQL函数中的动态SELECT INTO

时间:2017-09-01 11:09:18

标签: postgresql variable-assignment plpgsql dynamic-sql stored-functions

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

假设我有一个名为tb_name的变量,它填充在FOR的{​​{1}}循环中。现在我有一个名为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 tb_name的数据类型应该是什么?

2 个答案:

答案 0 :(得分:4)

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;

注释

解决your comment:传递 ,使用USING子句,如:

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

相关:

答案 1 :(得分:1)

您似乎想要const OnboardingComplete = ({ first_name, last_name, id, mutate }) => { 的{​​{1}}占位符,以便将您的变量视为标识符。另外,%I子句应该在之外准备好的语句。

FORMAT