我从Postgress开始,我需要使用四个id作为参数进行查询,这些可以是NULL,只有第一个是必需的,所以我试图获取包含每个id的数据的数据列表。如何在WHERE条件中检查id参数是否为非NULL。 我会给你一个例子(不工作)
CREATE OR REPLACE FUNCTION sp_lock(
IN p_id_1 character varying,
IN p_id_2 character varying DEFAULT NULL,
IN p_id_3 character varying DEFAULT NULL,
IN p_id_4 character varying DEFAULT NULL)
RETURNS SETOF character varying AS
$BODY$
BEGIN
UPDATE stock
SET lock = 1
FROM (
SELECT s.id
FROM stock s
WHERE
(ls.id = p_id_1 or p_id_1 is null) OR
(ls.id = p_id_2 or p_id_2 is null) OR
(ls.id = p_id_3 or p_id_3 is null) OR
(ls.id = p_id_4 or p_id_4 is null) AND
ls.lock = 0
FOR UPDATE OF s
) i
WHERE i.id = stock.id;
这里我需要首先检查,如果param是非NULL,然后连接到条件,使用OR exp。
答案 0 :(得分:1)
您可以在where条件
中使用in
operator
WHERE
s.id in (p_id_1, p_id_2, p_id_3, p_id_4) AND
s.lock = 0;
是的,你不需要子查询:
UPDATE stock
SET lock = 1
WHERE
id in (p_id_1, p_id_2, p_id_3, p_id_4) AND
lock = 0;
完全相同但更快。