创建函数:$$ 处或附近的语法错误

Create Function: Syntax Error at or near $$

我是 Postgres 的初学者,我想使用一个函数从 table 中自动删除一列。但是它给了我我在标题中提到的错误。

这是我的代码:

create function dropColumn(table_name text,col_name text) returns void as $$
ALTER TABLE  DROP COLUMN IF EXIST ;
$$
language 'psql';

错误:

ERROR:  syntax error at or near "$$
language 'psql';
create function dropColumn(table_name text,col_name text) returns
void $$"
LINE 1: $$

有什么问题吗?我该如何解决这个问题?

您忘记了关键字 AS:

create function dropColumn(table_name text,col_name text) returns void AS $$
ALTER TABLE  DROP COLUMN IF EXIST ;
$$
language 'psql';

你的函数几乎所有地方都是错误的。最重要的是,您不能在普通 SQL 中参数化标识符。您需要在 plpgsql 函数(或任何其他支持它的过程语言)中使用 SQL 和 EXECUTE 。这将完成这项工作:

CREATE OR REPLACE FUNCTION drop_column(table_name text, col_name text)
  RETURNS void AS
$func$
BEGIN
   EXECUTE format('ALTER TABLE %I DROP COLUMN IF EXISTS %I'
                 , table_name, col_name);
END
$func$
LANGUAGE plpgsql;

致电:

SELECT drop_column('my_tbl', 'my_column');

开始于 reading the manual here and study some of the related questions and answers on SO.

要特别注意正确防范SQL注入:

  • Table name as a PostgreSQL function parameter