【问题标题】:Dynamic SELECT INTO in PL/pgSQL functionPL/pgSQL 函数中的动态 SELECT INTO
【发布时间】:2018-02-10 10:40:26
【问题描述】:

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

假设我有一个名为tb_name 的变量,它填充在来自information_schema.tables 的FOR 循环中。现在我有一个名为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和tc的数据类型应该是什么?

【问题讨论】:

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


【解决方案1】:
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;

相关:

【讨论】:

  • EXECUTE format('SELECT count() FROM %I.%I', _schema, _tb_name) 如何在此选择中使用 where 条件?比如 EXECUTE format('SELECT count() FROM %I.%I WHERE some_column=user_def_variable ', _schema, _tb_name,column_name)
  • @Karthik:我附加了一个答案。请记住以 question 的形式提出问题。评论不是地方。
【解决方案2】:

您似乎想要FORMAT 的占位符%I,以便它将您的变量视为标识符。此外,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

【讨论】:

  • 在没有模式限定的情况下使用表名将是一个偷偷摸摸的错误。我添加了一些解释。
猜你喜欢
  • 2012-08-12
  • 2012-04-24
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
相关资源
最近更新 更多