在数据库查询中设置标志值

Set flag value in DB query

如果特定 ID 存在,我的查询会更新 table,否则它会插入一个新值。

我想实现类似 -:

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;

当 运行 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在table中是唯一的)。更新为 1,插入为 0。恰恰与你想要的相反。但是,您可以轻松地从中导出您的标志:v_flag := 1 - v_count.

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;