使用从psql命令行传入的变量,在函数中

时间:2016-01-12 21:14:33

标签: postgresql

我无法弄清楚如何在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
                    ^

1 个答案:

答案 0 :(得分:0)

也许我已经过度简化了你的任务(随时告诉我是不是这样),但为什么不创建这样的功能:

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字段,所以可以想象您的目标表存在于另一个模式中,并且实际的drop命令将失败,因为它在默认模式中不存在。