如何转义百分号 "EXECUTE format('blah')"

How to escape a percent sign in "EXECUTE format('blah')"

我有两个table,例如:

CREATE TABLE table_1
(
    one_column   INTEGER,
    two_column   INTEGER,
    three_column INTEGER
);

CREATE TABLE table_2
(
    id        SERIAL,
    column_1  INTEGER,
    column_2  INTEGER,
    column_3  INTEGER,
    name      TEXT,
    step      INTEGER
);

我还有一个接收多个参数的存储函数。在函数中,我使用对 EXECUTE format() 的调用将 INSERT 一行插入 table,类似这样...

CREATE OR REPLACE PROCEDURE function_p (
    p_name TEXT DEFAULT '',
    p_step INT DEFAULT NULL
    )
LANGUAGE plpgsql AS $$
BEGIN
  EXECUTE format('
    INSERT INTO table_2 (column_1,column_2,column_3,name,step)
    SELECT one_column, two_column,three_column,%L,%s
    FROM table_1',p_name,p_step);   
END;
$$

(感谢@jim-jones)

但是,在我的 'actual' 函数中,我在 SELECT 中也有一个 INNER JOIN,它具有类似以下条件的东西...

    ON (month_diff(d, now()::DATE) % month_interval) = 0

我收到类似 unrecognized format() type specifier " " 这样的错误,我在想我是否需要转义 '%' 符号并且,如果是这样,如何?是“\%”还是“%%”还是其他?我试过这些但都失败了。

你的问题一定出在其他地方。 %% 成功了:

SELECT
  format('%s%%',42),
  format('%1s%%',42),
  format('%2$s%% - %1$s%%',42,73); -- $ index for customized order

 format | format |  format   
--------+--------+-----------
 42%    | 42%    | 73% - 42%
(1 row)

这在the documentation中提到:

In addition to the format specifiers described above, the special sequence %% may be used to output a literal % character.