2015-09-25 40 views
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。

+0

這個查詢究竟有什麼問題? – Mureinik

+0

我不確定如果p_id_3爲空,會發生什麼,例如,只能確保p_id_1總是會來。 –

回答

1

你可以使用in operator在where條件

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; 

不完全一樣,但速度更快。

相關問題