【发布时间】:2012-05-29 03:44:09
【问题描述】:
我想在 Postgres 函数中将表名作为参数传递。我试过这段代码:
CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS integer
AS $$
BEGIN
IF EXISTS (select * from quote_ident($1) where quote_ident($1).id=1) THEN
return 1;
END IF;
return 0;
END;
$$ LANGUAGE plpgsql;
select some_f('table_name');
我得到了这个:
ERROR: syntax error at or near "."
LINE 4: ...elect * from quote_ident($1) where quote_ident($1).id=1)...
^
********** Error **********
ERROR: syntax error at or near "."
这是我改成select * from quote_ident($1) tab where tab.id=1时遇到的错误:
ERROR: column tab.id does not exist
LINE 1: ...T EXISTS (select * from quote_ident($1) tab where tab.id...
quote_ident($1) 可能有效,因为没有where quote_ident($1).id=1 部分我得到1,这意味着选择了某些东西。为什么第一个quote_ident($1) 可以工作而第二个不能同时工作?又该如何解决呢?
【问题讨论】:
-
我知道这个问题有点老了,但我在寻找另一个问题的答案时发现了它。您的函数不能只查询 informational_schema 吗?我的意思是,这在某种程度上就是为了让您查询并查看数据库中存在哪些对象。只是一个想法。
-
@DavidS 感谢您的评论,我会尝试的。
标签: function postgresql plpgsql dynamic-sql identifier