gpt4 book ai didi

arrays - 具有 IN 条件的存储过程语法

转载 作者:行者123 更新时间:2023-11-29 11:55:16 29 4
gpt4 key购买 nike

(1)

=>CREATE TABLE T1(id BIGSERIAL PRIMARY KEY, name TEXT);
CREATE TABLE

(2)

=>INSERT INTO T1
(name) VALUES
('Robert'),
('Simone');
INSERT 0 2

(3)

SELECT * FROM T1;
id | name
----+--------
1 | Robert
2 | Simone
(2 rows)

(4)

CREATE OR REPLACE FUNCTION test_me(id_list BIGINT[]) 
RETURNS BOOLEAN AS
$$
BEGIN
PERFORM * FROM T1 WHERE id IN ($1);
IF FOUND THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END;
$$
LANGUAGE 'plpgsql';
CREATE FUNCTION

我的问题是调用程序时。我无法在网上找到展示如何传递 BIGINT 类型(或整数等)值列表的示例。

我尝试了以下但没有成功(语法错误):

第一种语法:

eway=> SELECT * FROM test_me('{1,2}'::BIGINT[]);
ERROR: operator does not exist: bigint = bigint[]
LINE 1: SELECT * FROM T1 WHERE id IN ($1)
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
QUERY: SELECT * FROM T1 WHERE id IN ($1)
CONTEXT: PL/pgSQL function test_me(bigint[]) line 3 at PERFORM

第二种语法:

eway=> SELECT * FROM test_me('{1,2}');
ERROR: operator does not exist: bigint = bigint[]
LINE 1: SELECT * FROM T1 WHERE id IN ($1)
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
QUERY: SELECT * FROM T1 WHERE id IN ($1)
CONTEXT: PL/pgSQL function test_me(bigint[]) line 3 at PERFORM

第三种语法:

eway=> SELECT * FROM test_me(ARRAY [1,2]);
ERROR: operator does not exist: bigint = bigint[]
LINE 1: SELECT * FROM T1 WHERE id IN ($1)
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
QUERY: SELECT * FROM T1 WHERE id IN ($1)
CONTEXT: PL/pgSQL function test_me(bigint[]) line 3 at PERFORM

关于有效语法的任何线索?

这就像解析器试图在 PEFORM REQUEST 中将 BIGINT 转换为 BIGINT[] 但它对我来说没有任何意义......

最佳答案

传递数组的所有语法变体都是正确的

问题出在函数内部的表达式上。您可以使用 ANY construct 进行测试喜欢@Mureinik provided或许多其他语法变体。在任何情况下都使用 EXISTS 表达式运行测试:

CREATE OR REPLACE FUNCTION test_me(id_list bigint[]) 
RETURNS bool AS
$func$
BEGIN
IF EXISTS (SELECT 1 FROM t1 WHERE id = ANY ($1)) THEN
RETURN true;
ELSE
RETURN false;
END IF;
END
$func$ LANGUAGE plpgsql STABLE;

注意事项

简单变体

当您返回一个 boolean 值时,它可以更简单。它可能只是为了演示,但作为概念证明:

CREATE OR REPLACE FUNCTION test_me(id_list bigint[]) 
RETURNS bool AS
$func$
SELECT EXISTS (SELECT 1 FROM t1 WHERE id = ANY ($1))
$func$ LANGUAGE sql STABLE;

同样的结果。

关于arrays - 具有 IN 条件的存储过程语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352150/

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