【问题标题】:Using variable passed in from psql command line, in function在函数中使用从 psql 命令行传入的变量
【发布时间】:2016-04-17 16:09:29
【问题描述】:

我不知道如何访问我的 plpgsql 函数中的变量。我在 Cygwin 下使用 postgres 9.5。

functions.sql

-- this works fine
\echo Recreate = :oktodrop

CREATE OR REPLACE FUNCTION drop_table(TEXT) RETURNS VOID AS
$$
BEGIN
    IF EXISTS ( SELECT * FROM information_schema.tables WHERE table_name = $1 ) THEN
        -- syntax error here:
        IF (:oktodrop == 1 ) THEN
            DROP TABLE $1;
        END IF;
    END IF;
END;
$$
language 'plpgsql';

psql.exe -v oktodrop=1 -f functions.sql

Password:
Recreate = 1
psql:functions.sql:13: ERROR:  syntax error at or near ":"
LINE 5:         IF (:oktodrop == 1 ) THEN
                    ^

【问题讨论】:

  • 一个简单的select $$ :oktodrop $$ 也不会插入变量:字符串中的内容超出了 psql 解析器的范围。除此之外,PG 9.5 提供了DROP TABLE IF EXISTS tablename;,所以你可能根本不需要那个函数。

标签: postgresql


【解决方案1】:

也许我过分简化了你的任务(如果是这种情况,请随时告诉我),但为什么不创建这样的函数:

CREATE OR REPLACE FUNCTION drop_table(tablename TEXT, oktodrop integer)
RETURNS text AS
$$
DECLARE
  result text;
BEGIN
  IF EXISTS ( SELECT * FROM information_schema.tables WHERE table_name = tablename ) THEN
      IF (oktodrop = 1 ) THEN
        execute 'DROP TABLE ' || tablename;
        result := 'Dropped';
      ELSE
        result := 'Not Okay';
      END IF;
    ELSE
      result := 'No such table';
    END IF;
  return result;
END;
$$
language 'plpgsql';

那么实现将是:

select drop_table('foo', 1);

我还要注意,由于您没有指定table_schema 字段,因此可以想象您的目标表存在于另一个架构中,并且实际的删除命令将失败,因为它不存在于默认架构中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2014-06-10
    相关资源
    最近更新 更多