PL/pgSQL 中的变量替换
我有一个根据提供的参数动态生成的选择语句。问题是postgresql总是说:
WHERE的参数必须是布尔类型,而不是字符变化类型
无论参数是什么。我错过了什么吗?
CREATE OR REPLACE FUNCTION getuid(name character varying) RETURNS integer AS $$
DECLARE
statement varchar;
uid integer;
BEGIN
IF ($1 = '') THEN
statement := 'TRUE';
statement := CAST(statement AS BOOLEAN);
ELSE
statement := 'users.keywords ILIKE''' || '%' || $1 || '%''';
END IF;
SELECT INTO uid id FROM users WHERE "statement";
RETURN uid;
END;
$$ LANGUAGE plpgsql
I have a select statement that is generated dynamically based on the supplied parameter. The problem is that postgresql always says:
argument of WHERE must be type boolean, not type character varying
no matter what the parameter is. Did I miss anything?
CREATE OR REPLACE FUNCTION getuid(name character varying) RETURNS integer AS $
DECLARE
statement varchar;
uid integer;
BEGIN
IF ($1 = '') THEN
statement := 'TRUE';
statement := CAST(statement AS BOOLEAN);
ELSE
statement := 'users.keywords ILIKE''' || '%' || $1 || '%''';
END IF;
SELECT INTO uid id FROM users WHERE "statement";
RETURN uid;
END;
$ LANGUAGE plpgsql
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想要在函数内生成动态命令。您还可以使用两个不同的部分:
You need EXECUTE if you want to generate dynamic commands inside a function. You could also use two different sections:
EXECUTE
是 PL/pgSQL 语句而不是 SQL 语句。因此,您必须将动态查询包装到 PL/pgSQL 存储过程中。请小心变量替换,并且在构建查询时不要忘记使用
quote_literal()
或quote_nullable()
。请查看此处的文档: http:// /www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATMENTS-EXECUTING-DYN
EXECUTE
is a PL/pgSQL statement and not SQL statement. So you have to wrap your dynamic query into PL/pgSQL stored procedure.Be careful about variable substitution and do not forget to use
quote_literal()
orquote_nullable()
when building up you query.Have look in documentation here: http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN