表名作为PostgreSQL函数参数我想在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)工作和第二次不是同时进行吗?这怎么能解决呢?
3 回答
jeck猫
TA贡献1909条经验 获得超7个赞
IF EXISTS (<query>)
query
CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS integer AS $$DECLARE v int;BEGIN EXECUTE 'select 1 FROM ' || quote_ident(param) || ' WHERE ' || quote_ident(param) || '.id = 1' INTO v; IF v THEN return 1; ELSE return 0; END IF;END;$$ LANGUAGE plpgsql;
添加回答
举报
0/150
提交
取消