运算符不存在:字符 varying[] = 文本

operator does not exist: character varying[] = text

提问人:abhi1489 提问时间:9/6/2023 更新时间:9/7/2023 访问量:131

问:

我有一个postgreSQL函数,它将文本数组作为输入参数之一:


CREATE OR REPLACE FUNCTION report.fn_get_metrics(
    from_date timestamp without time zone,
    to_date timestamp without time zone,
    location_ids text[])
    RETURNS TABLE(demand_new_count bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000
AS $BODY$
BEGIN
    RETURN QUERY
    WITH 
    cte_pos AS (
    SELECT
        COUNT(DISTINCT job_id) AS demand_new_count,
    FROM report.pg_job_data pjd
    WHERE creation_date >= from_date AND creation_date <= to_date
    AND (location_ids IS NULL OR location_id IN (SELECT unnest(location_ids)))
)
    SELECT
        demand_new_count
    FROM cte_pos;
END;
$BODY$;

我正在尝试通过将值数组传递给此参数来查询函数:

SELECT * FROM report.fn_get_metrics(
    '2023-01-01'::timestamp, -- from_date
    '2023-06-30'::timestamp, -- to_date
    ARRAY['638a4f2c-11c4-4e15-ae78-d6bf01ef2fad']
);

我尝试将值数组类型转换为uuid,如下所示:

SELECT * FROM report.fn_get_metrics(
    '2023-01-01'::timestamp, -- from_date
    '2023-06-30'::timestamp, -- to_date
    ARRAY['638a4f2c-11c4-4e15-ae78-d6bf01ef2fad']::UUID[]
);

但它似乎不起作用。我们不能为函数中的输入参数使用 varchar[] 或 uuid[] 类型。关于如何解决此问题的任何指导将不胜感激

SQL PostgreSQL 函数

评论


答:

0赞 Pavel Stehule 9/6/2023 #1

你应该改用运算符,比如= ANYIN

坏:

-- should not to work
SELECT * FROM foo WHERE col IN (ARRAY[1,2,3]);

正确:

SELECT * FROM foo WHERE col = ANY(ARRAY[1,2,3]);

评论

0赞 abhi1489 9/6/2023
还行。但它仍然没有解决运营商不存在的问题
0赞 Nnaemeka Daniel John 9/6/2023 #2

您应该在函数中更改参数的数据类型,以便它可以接受 UUID 数组而不是文本数组。按以下方式修改函数参数:location_ids


CREATE OR REPLACE FUNCTION report.fn_get_metrics(
    from_date timestamp without time zone,
    to_date timestamp without time zone,
    location_ids uuid[])

然后你就可以这样称呼它了:

SELECT * FROM report.fn_get_metrics(
    '2023-01-01'::timestamp, -- from_date
    '2023-06-30'::timestamp, -- to_date
    ARRAY['638a4f2c-11c4-4e15-ae78-d6bf01ef2fad']::UUID[]
);
0赞 Adrian Klaver 9/6/2023 #3

有条件的答案。

这是正确的,没有运算符在数组和文本值之间进行比较。operator does not exist: character varying[] = text=

我唯一能看到这种情况发生的地方是:

location_id IN (SELECT unnest(location_ids))

数据类型是什么?location_id

我打赌:character varying[]

select 
    array['one', 'two']::varchar[] in (unnest(array['one', 'two'])); 

ERROR:  operator does not exist: character varying[] = text

一个更完整的答案等待着你提供更多信息,关于你的类型,以及你是要做一个到比较还是到比较。location_idarrayarrayvarchararray