为什么 postgres 不接受函数参数作为表名
我正在尝试使用下面的函数更新表格。表名是函数参数。运行此函数会导致错误:
错误:“$1”处或附近的语法错误 LINE 1: (SELECT * FROM $1 ORDER BY $2 )
我尝试使用 EXECUTE 语句和 quote_ident 函数,但到目前为止没有成功。我确信我忽略了一些简单的事情......
CREATE OR REPLACE FUNCTION createdefaultorder(table_name varchar, sort_column varchar)
RETURNS integer AS
$BODY$
DECLARE
rRec RECORD;
counter integer := 0;
BEGIN
FOR rRec IN (SELECT * FROM table_name ORDER BY sort_column) LOOP
UPDATE table_name SET row_number = counter WHERE id = rRec.id;
counter := counter + 1;
END LOOP;
RETURN 0;
END;
$BODY$
LANGUAGE plpgsql;
I'm trying the update a table using the function below. The table name is a function argument. Running this function results in the error:
ERROR: syntax error at or near "$1"
LINE 1: (SELECT * FROM $1 ORDER BY $2 )
I tried using the EXECUTE statement and the quote_ident function, but without success sofar. I'm sure I'm overlooking something simple...
CREATE OR REPLACE FUNCTION createdefaultorder(table_name varchar, sort_column varchar)
RETURNS integer AS
$BODY$
DECLARE
rRec RECORD;
counter integer := 0;
BEGIN
FOR rRec IN (SELECT * FROM table_name ORDER BY sort_column) LOOP
UPDATE table_name SET row_number = counter WHERE id = rRec.id;
counter := counter + 1;
END LOOP;
RETURN 0;
END;
$BODY$
LANGUAGE plpgsql;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
EXECUTE
和quote_ident
是正确的解决方案。如果您遇到问题,您可能需要显示该代码。Using
EXECUTE
andquote_ident
is the correct solution. If you have trouble with that, you might want to show that code.Execute
和quote_ident
是该问题的解决方案:PostgreSQL 8.4 手册Execute
andquote_ident
are the solution to that problem: PostgreSQL 8.4 Manual您必须在动态查询执行中使用 EXECUTE 和 quote_ident(),如下所示:
You must use EXECUTE and quote_ident() in a dynamic query execution like this: