2016-11-16 28 views
0

如果存在特定的ID,我的查詢會更新一個表,否則它會插入一個新值。在數據庫查詢中設置標誌值

我想要實現像 - :

if(exists){ 
    update table, 
    flag = 0} 
else{ 
    insert into table, 
    flag = 1} 
return flag; 

我現有的查詢是

BEGIN 
merge into FCM_DEVICE_REGISTRATION u 
using dual 
on (device_ad_id = 1) 
when matched then 
      update set fcm_notification_id='N', 
         last_update_date = SYSDATE 
when not matched then 
insert (device_ad_id,fcm_notification_id) values (1,'Y'); 
END; 
+0

您是否正在使用'INSERT INTO ... ON DUPLICATE KEY UPDATE'? –

+0

什麼是你使用的數據庫引擎? –

+0

@LelioFaieta oracle 12g –

回答

1

當運行MERGE可以使用SQL%ROWCOUNT獲得受影響的行數。但是,您不能確定是否應用了插入或更新,甚至不知道已更新了多少行以及插入了多少行。因此,您必須事先檢查相關行是否存在。而且,那麼你知道是否要更新或插入自己,所以你不需要MERGE了。

DECLARE 
    v_count integer; 
BEGIN 
    select count(*) into v_count 
    from fcm_device_registration 
    where device_ad_id = 1; 

    if v_count = 0 then 
    insert into fcm_device_registration 
     (device_ad_id, fcm_notification_id) values (1, 'Y'); 
    else 
    update fcm_device_registration 
    set fcm_notification_id = 'N', last_update_date = sysdate 
    where device_ad_id = 1; 
    end; 
END; 

變量v_count包含0或1(如你說的device_ad_id是獨特的表)。更新爲1,插入爲0。恰恰與你想要的相反。但是,您可以輕鬆地從此導出標誌:v_flag := 1 - v_count

+0

因此,在一次數據庫調用中沒有辦法做到這一點? –

+1

這是一個數據庫調用。如果你的意思是「一個SQL語句」,那麼不是,但是SQL中沒有變量,所以你不能從插入,更新,刪除或合併中獲得「標誌」。 –

1
BEGIN 
update fcm_device_registration 
set fcm_notification_id='N', 
last_update_date = SYSDATE 
where device_ad_id = 1; 
--in case of no update 
if sql%rowcount = 0 then 
    insert into fcm_device_registration(device_ad_id,fcm_notification_id) values (1,'Y'); 
    dbms_output.put_line('insert'); 
else 
    dbms_output.put_line('update');-- in case of record update 
end if; 
END; 
+0

如果您發現此解決方案良好,請將其標記爲答案。 –