gpt4 book ai didi

sql - 从 plpgsql 标识符中的连接字符串中删除双引号

转载 作者:行者123 更新时间:2023-11-29 12:17:32 24 4
gpt4 key购买 nike

我编写了以下函数,它从另一个表“parameters_ltree_{time_created}”返回记录,其中 time_created 是 historical_ltree 表中的一列。

CREATE OF REPLAE function get_my_path(date_string text, path_arg ltree) RETURNS SETOF  ltree AS
$BODY$
DECLARE
p text;
d text;
BEGIN
d := quote_ident(date_string);
p := 'parameters_ltree_';
RETURN QUERY EXECUTE format(
'SELECT path from %I' || '%I
WHERE path = %I
ORDER BY path
LIMIT 1'
, p, date_string, path_arg);

END
$BODY$
LANGUAGE plpgsql;

SELECT id, path, get_my_path(to_char(time_created, 'YYYYMMDD')), path) from historical_ltree

该函数可以编译,但是当我在底部运行 SELECT 查询时,它会抛出一个语法错误:

ERROR: relation "parameters_ltree_" does not exist
LINE 1: SELECT path FROM parameters_ltree_"20161201"
^

我尝试了很多不同的方法来使连接正常工作,但都无济于事,包括将 date_string 作为数字传递。

最佳答案

尝试更改为:

    RETURN QUERY EXECUTE format(
'SELECT path from %I
WHERE path = %L
ORDER BY path
LIMIT 1'
, 'parameters_ltree_'||date_string, path_arg);

https://www.postgresql.org/docs/current/static/functions-string.html

s formats the argument value as a simple string. A null value is treated as an empty string.

I treats the argument value as an SQL identifier, double-quoting it if necessary. It is an error for the value to be null (equivalent to quote_ident).

L quotes the argument value as an SQL literal. A null value is displayed as the string NULL, without quotes (equivalent to quote_nullable).

关于sql - 从 plpgsql 标识符中的连接字符串中删除双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44718136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com