2015-07-13 81 views
0

我正在寫一個Postgres函數,它應該從3個表中連續刪除。如何檢查表中的元素是否存在?

該關係從mobgroupdata - > mobilenums - >終端中刪除,當我在mobgroupdata中沒有元素時,我想從mobilenums中刪除,然後從終端中刪除。但是,應該是什麼條件。我試過

IF mRec.id != 0,但它沒有工作,比我試過exists,它也沒有工作。另外,當我從數據庫中創建我的select聲明並且mobgroupdata的id不存在時,代碼就會中斷,但是當我選擇它包含在所有表中的元素時,它就會工作。是否有人知道應該如何使if語句有效?

CREATE OR REPLACE FUNCTION "Delete_From_Terminals_Casc_final12"(
"Id_list" bigint, 
"Curuser_id" bigint) 
    RETURNS SETOF term_mgd_mobnums AS 
$BODY$ 
declare 
    mRec "term_mgd_mobnums"%ROWTYPE; 

BEGIN 

    for mRec in select mn."id_terminals", t.sn , t.imei ,t.les ,t.category ,t.model ,t.tswv ,t.status ,t.activation_date ,t.deactivation_date ,t.paytype ,t.ip_address ,t.pin1 ,t.pin2 ,t.puk1 ,t.puk2 ,t.notes ,t.units ,t.validtill, t.responsible_user,t.id_clients,t.currentuser, t.isn, 
md.id_mobilenums, mn.current_status, mn.start_date ,mn.streason ,mn.unit ,mn.mobnumber ,mn.service ,mn.status as mn_status,mn.activator ,mn.responsible_department,mn.date_changed ,mn.reason ,mn.installed_on ,mn.usedby ,mn.regnumber ,mn.responsible_user as mn_responsible_user ,mn.description, 
md.id,md.les1 ,md.les2,md.les3,md.les4,md.les5,md.member1 ,md.member2,md.member3,md.member4,md.member5,md.user1 ,md.user2,md.user3,md.user4,md.user5,md.pass1 ,md.pass2,md.pass3,md.pass4,md.pass5 from terminals t 
inner join mobilenums mn on t."id" = mn."id_terminals" 
inner join mobgroupdata md on md."id_mobilenums" = mn."id" 
where mn."id_terminals" = $1 
loop  

IF exists THEN 
PERFORM "Delete_From_Mobgroupdata2"(mRec.id,$2); 
PERFORM "Delete_From_Mobilenums"(mRec.id_mobilenums::text,$2); 
PERFORM "Delete_From_Terminals"(mRec.id_terminals::text,$2); 
    ELSE 
PERFORM "Delete_From_Mobilenums"(mRec.id_mobilenums::text,$2); 
PERFORM "Delete_From_Terminals"(mRec.id_terminals::text,$2); 
END IF; 
RETURN NEXT mRec; 
    end loop; 
    return; 
end;$BODY$ 
LANGUAGE plpgsql VOLATILE 
COST 100 
ROWS 1000; 
ALTER FUNCTION "Delete_From_Terminals_Casc_final12"(bigint, bigint) 
    OWNER TO postgres; 
+0

這可以優雅地解決,但我不清楚精確的算法應該是什麼。如果你能澄清這個問題,你一定會得到答案。 –

回答

1

兩個問題,你的代碼,如果我正確地讀你的問題:

  1. 您正在使用INNER JOIN加入到mobgroupdata。這隻會檢索所有表中存在的行的結果。改爲使用LEFT OUTER JOIN
  2. 您試過mRec.id != 0,但您正在尋找NULL,而不是00NULL在SQL中不是一回事。你想要的條件是mRec.id IS NOT NULL
+0

非常感謝! – TodorBalabanski

+0

如果這回答您的問題令您滿意,請點擊左邊的綠色複選標記接受答案。這將標記問題爲答案,並給我假裝我渴望的互聯網點。 –

+0

是的,這回答我的問題,我忘了接受答案,比你:) – TodorBalabanski