SQL 中有转义变量的机制吗?

Is there a mechanism in SQL to escape a variable?

我将在 PostgreSQL 中编写一个接受变量的存储过程(我对 SQL 的了解接近于零,如果问题很明显,我深表歉意)。由于这个变量将在调用中逐字使用,我想确保它被正确转义以避免注入。

有没有我可以将变量包装在其中的函数,它可以正确地进行转义?

我特别想在 SQL 中执行此操作,而不是在调用 SQL 查询的代码中清理输入(该变量)(这可能更容易)。

我很惊讶没有找到任何关于此类功能的重要文档,这让我相信这不是标准做法。我能得到的最接近的是 lexer source code of Postgresql 但这超出了我理解这是否是所提到的正确转义的能力(这将导致 string 被用作 u&’stringuescape’’’ ,看起来很野蛮)

PostgreSQL 中有几个引用函数,记录在 https://www.postgresql.org/docs/current/functions-string.html

quote_ident(string text)    text    Return the given string suitably quoted to be used as an identifier in an SQL statement string. Quotes are added only if necessary (i.e., if the string contains non-identifier characters or would be case-folded). Embedded quotes are properly doubled. See also Example 40-1.   quote_ident('Foo bar')  "Foo bar"
quote_literal(string text)  text    Return the given string suitably quoted to be used as a string literal in an SQL statement string. Embedded single-quotes and backslashes are properly doubled. Note that quote_literal returns null on null input; if the argument might be null, quote_nullable is often more suitable. See also Example 40-1.    quote_literal(E'O\'Reilly') 'O''Reilly'
quote_literal(value anyelement) text    Coerce the given value to text and then quote it as a literal. Embedded single-quotes and backslashes are properly doubled. quote_literal(42.5) '42.5'
quote_nullable(string text) text    Return the given string suitably quoted to be used as a string literal in an SQL statement string; or, if the argument is null, return NULL. Embedded single-quotes and backslashes are properly doubled. See also Example 40-1.    quote_nullable(NULL)    NULL
quote_nullable(value anyelement)    text    Coerce the given value to text and then quote it as a literal; or, if the argument is null, return NULL. Embedded single-quotes and backslashes are properly doubled.   quote_nullable(42.5)    '42.5'

但是,如果您设计的过程是从字符串准备 SQL,则应改用查询参数。

PREPARE fooplan (int, text, bool, numeric) AS
    INSERT INTO foo VALUES(, , , );
EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);

https://www.postgresql.org/docs/current/sql-prepare.html

中阅读更多内容