如何检查表中的元素是否存在?

时间:2015-07-13 13:45:07

标签: postgresql plpgsql

我正在编写Postgres函数,该函数应该连续删除3个表。

关系是从mobgroupdata中删除 - > mobilenums - >终端,当我在mobgroupdata中没有元素时,我想从mobilenums中删除,然后从终端中删除。但应该是什么条件。我试过

IF mRec.id != 0,但它不起作用,比我尝试使用exists,它也没有用。此外,当我从DB发出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;

1 个答案:

答案 0 :(得分:1)

如果我正确地阅读您的问题,您的代码会遇到两个问题:

  1. 您正在使用INNER JOIN加入mobgroupdata。这将仅检索所有表中存在的行的结果。请改用LEFT OUTER JOIN
  2. 您尝试了mRec.id != 0,但您正在寻找NULL,而不是00NULL在SQL中不是一回事。您想要的条件是mRec.id IS NOT NULL