我有这个 plpgsql 函数:
CREATE OR REPLACE FUNCTION func_example(
IN check_ids INT [],
OUT recs REFCURSOR,
OUT po_result_code TEXT
) RETURNS RECORD LANGUAGE plpgsql AS $$
BEGIN
OPEN recs FOR
SELECT *
FROM my_table t
JOIN my_another_table tt on tt.tid = t.id
WHERE t.enabled = TRUE
AND tt.some = 1
AND (
check_ids IS NULL OR check_ids.count = 0 /* <-- problem here */
OR t.id = ANY (check_ids)
);
po_result_code := 0;
RETURN;
END;
$$;
调用它会导致错误消息:
Error: [42P01] ERROR: missing FROM-clause entry for table "check_ids" SQL state: 42P01
如何检查'argument is null or value in argument'?
一些示例数据:
CREATE TABLE my_table (
id INT,
enabled BOOLEAN DEFAULT TRUE
);
CREATE TABLE my_another_table (
tid INT,
"some" INT DEFAULT 1,
CONSTRAINT t_another_to_my_fk FOREIGN KEY (tid) REFERENCES my_table (id)
);
INSERT INTO my_table (id, enabled) VALUES (1, TRUE);
INSERT INTO my_another_table (tid, "some") VALUES (1, 1);
最佳答案
为了让 NULL 和空数组通过,替换:
(t.id = ANY (check_ids) OR check_ids IS NULL OR check_ids.count = 0) -- illegal syntax
用单个表达式:
(t.id = ANY (check_ids) OR <b>(check_ids = '{}') IS NOT FALSE</b>)
这也行,但有点慢:
(t.id = ANY (check_ids) OR check_ids IS NULL OR check_ids = '{}')
与字符串类型密切相关的详细解释:
但是,您的实际问题要求的是不同:
How to check 'argument is null or value in argument'?
这会简化为:
(t.id = ANY (check_ids) OR check_ids IS NULL)
所有这些都属于 SQL 领域,与 PL/pgSQL 无关。
关于sql - 如何在查询的 WHERE 子句中检查 'any or limited'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50346286/