PL / pgSQL函数中的动态SELECT INTO

问题描述 投票:4回答:2

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

假设我有一个名为tb_name的变量,它填充了FORinformation_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_nametc的数据类型应该是什么?

postgresql variable-assignment plpgsql dynamic-sql stored-functions
2个回答
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;

Notes


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

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

有关:


1
投票

看起来你想要%IFORMAT占位符,以便它将你的变量视为标识符。此外,INTO条款应该超出准备好的声明。

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(*) from %I', tb_name) INTO tc;
END LOOP
© www.soinside.com 2019 - 2024. All rights reserved.