1
我以Postgress開始,我需要以四個ID作爲參數進行查詢,這些可以是NULL,只有第一個是必需的,所以我試圖獲得一個包含每個id數據的數據列表。我如何檢查id參數是否在WHERE條件內不爲NULL。 我給你一個例子(沒有工作)如何在Postgres函數中進行條件查詢
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;
在這裏,我首先需要檢查,如果該參數是NOT NULL,然後拼接的條件,用或EXP。
這個查詢究竟有什麼問題? – Mureinik
我不確定如果p_id_3爲空,會發生什麼,例如,只能確保p_id_1總是會來。 –