gpt4 book ai didi

postgresql - 错误 : op ANY/ALL (array) requires array on right side in Postgres Function

转载 作者:行者123 更新时间:2023-11-29 12:19:23 26 4
gpt4 key购买 nike

我在我的 PostgreSQL 函数中遇到错误,我通过传递两个参数来过滤我的数据。下面是我的函数和表结构,请告诉我我在哪里做错了什么

CREATE TABLE table_2(
id_col text,
name_col text);

INSERT INTO table_2(id_col, name_col)
VALUES (1, 'A'),(2, 'B'),(3, 'C'),
(4, 'D'),(5, 'E'),(6, 'F');

CREATE OR REPLACE FUNCTION test_str_1(IN param_name_col text,
VARIADIC integer[], OUT id_col text, OUT name_col text)
RETURNS SETOF record AS
$BODY$
BEGIN
return query
SELECT t2.id_col,t2.name_col from table_2 t2
Where t2.name_col = param_name_col AND t2.id_col::int = ANY($1) ;
END
$BODY$
LANGUAGE plpgsql VOLATILE

SELECT test_str_1('A', 1,2,3);

最佳答案

你可以使用unnest:

CREATE OR REPLACE FUNCTION test_str_1(IN param_name_col text,
VARIADIC integer[], OUT id_col text, OUT name_col text)
RETURNS SETOF record AS
$BODY$
BEGIN
return query
SELECT t2.id_col,t2.name_col
from table_2 t2
Where t2.name_col = param_name_col
AND t2.id_col::int IN (SELECT * FROM unnest($2));
END
$BODY$
LANGUAGE plpgsql VOLATILE

SELECT test_str_1('A', 1,2,3);
-- "(1,A)"

或者只是将 ANY($1) 更改为 ANY($2)($1 - 是第一个参数,$2 - 是第二个):

CREATE OR REPLACE FUNCTION test_str_1(IN param_name_col text,
VARIADIC integer[], OUT id_col text, OUT name_col text)
RETURNS SETOF record AS
$BODY$
BEGIN
return query
SELECT t2.id_col,t2.name_col
from table_2 t2
Where t2.name_col = param_name_col
AND t2.id_col::int = ANY($2);
END
$BODY$
LANGUAGE plpgsql VOLATILE

SELECT test_str_1('A', 1,2,3);
-- "(1,A)"

$1 是值为 'A' 的第一个参数,ANY 需要数组类型的参数 ($2) .

关于postgresql - 错误 : op ANY/ALL (array) requires array on right side in Postgres Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34786324/

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