quote_ident() 是一个系统函数,用于格式化标识符以在SQL语句字符串中使用。
quote_ident() 在 PostgreSQL 7.1 中添加。
用法
quote_ident ( text ) → text
quote_ident() 通常与 quote_literal() 一起在 PL/pgSQL 中使用,以通过变量生成动态查询。
变更历史
- PostgreSQL 7.1
- 添加于 (commit daf1e3a7)
示例
基本用法
postgres=# SELECT quote_ident('Foo "Bar"');
quote_ident
---------------
"Foo ""Bar"""
(1 row)
实际用例
postgres=# CREATE TABLE "FOO" (id SERIAL); CREATE TABLE postgres=# SELECT pg_get_serial_sequence(quote_ident('FOO'), 'id'); pg_get_serial_sequence ------------------------ public."FOO_id_seq" (1 row)
PL/pgSQL 中的用法
postgres=# CREATE OR REPLACE FUNCTION dyntest (
tablename TEXT,
colname TEXT
)
RETURNS INT
LANGUAGE plpgsql STABLE
AS $$
DECLARE
intval INT;
BEGIN
EXECUTE 'SELECT ' || quote_ident(colname) ||
'FROM ' || quote_ident(tablename) ||
'LIMIT 1'
INTO intval;
RETURN intval;
END;
$$;
postgres=# INSERT INTO "FOO" values (1);
INSERT 0 1
postgres=# SELECT dyntest('FOO', 'ID');
dyntest
---------
1
(1 row)
参考资料
- PostgreSQL 文档: 其他字符串函数
