quote_literal() 是一个系统函数,用于将任意输入格式化为适当引用和转义的SQL字符串字面量。
quote_literal() 在 PostgreSQL 7.1 中被添加。
用法
quote_literal ( text ) → text
quote_literal ( anyelement ) → text
quote_literal() 常用于 PL/pgSQL 中,与 quote_nullable() 和 quote_ident() 一起,通过变量生成动态查询。
变更历史
- PostgreSQL 7.1
- 添加于(提交 daf1e3a7)
示例
quote_literal() 的基本用法示例
postgres=# SELECT quote_literal(1.2), quote_literal(array[1,2]);
quote_literal | quote_literal
---------------+---------------
'1.2' | '{1,2}'
(1 row)
PL/pgSQL 中的用法
postgres=# CREATE TABLE foo (val TEXT);
CREATE TABLE
postgres=# CREATE OR REPLACE FUNCTION littest (
someval TEXT
)
RETURNS VOID
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE 'INSERT INTO foo VALUES (' || quote_literal(someval) || ')';
END;
$$;
CREATE FUNCTION
postgres=# SELECT littest('bar');
littest
---------
(1 row)
postgres=# SELECT * FROM foo;
val
-----
bar
(1 row)
请注意,在上面的示例中,如果 someval 可能包含 NULL 值,则应使用 quote_nullable(),否则在连接的 EXECUTE 字符串中出现 NULL 值将导致整个字符串变为 NULL 并引发错误。
参考资料
- PostgreSQL 文档: 其他字符串函数
