在SQL中使用游标从一个表中取值更新另一个表的记录

温馨提示:本文最后更新于2025-06-04 12:48:31,某些文章具有时效性,若有错误或下载地址失效,请在文末评论区留言

在SQL中,使用游标(Cursor)从一张表取值并更新另一张表的记录是一种常见的需求,尤其是在需要基于复杂逻辑或条件更新多行数据时。

例如,将本地表 zzy_local_tab 中未标记(bz is null)的记录与远程表 isys.tran_bak_info@szcore 进行匹配,若远程表存在相同记录,则更新本地表的标记字段 bz=1 并同步远程表的 bak_id​​ 值。

图片[1]-在SQL中使用游标从一个表中取值更新另一个表的记录-十一张

SQL示例

declare
  v_card_id         zzy_local_tab.card_id%type;
  v_trans_type      zzy_local_tab.trans_type%type;
  v_eqp_id          zzy_local_tab.eqp_id%type;
  v_trans_date      zzy_local_tab.trans_date%type;
  v_trans_time      zzy_local_tab.trans_time%type;
  v_trans_amt       zzy_local_tab.trans_amt%type;
  v_bak_id          zzy_local_tab.bak_id%type;
  v_exist           int;
  cursor zzy_cursor is
    select card_id,trans_type,eqp_id,trans_date,trans_time,trans_amt,bak_id from zzy_local_tab 
        where bz is null
        order by trans_date,trans_time;
begin
  open zzy_cursor;
  fetch zzy_cursor into v_card_id,v_trans_type,v_eqp_id,v_trans_date,v_trans_time,v_trans_amt,v_bak_id;
  while zzy_cursor%found loop
    begin
      v_exist := 0;
      select count(*) into v_exist from isys.tran_bak_info@szcore where card_id = v_card_id and trans_type = v_trans_type and eqp_id = v_eqp_id and trans_date = v_trans_date and trans_time = v_trans_time and trans_amt = v_trans_amt;
      if v_exist > 0 then
        select bak_id into v_bak_id from isys.tran_bak_info@szcore where card_id = v_card_id and trans_type = v_trans_type and eqp_id = v_eqp_id and trans_date = v_trans_date and trans_time = v_trans_time and trans_amt = v_trans_amt and rownum < 2;
        update zzy_local_tab set bz = 1,bak_id = v_bak_id where card_id = v_card_id and trans_type = v_trans_type and eqp_id = v_eqp_id and trans_date = v_trans_date and trans_time = v_trans_time and trans_amt = v_trans_amt;
      end if;
      commit;
    end;
    fetch zzy_cursor into v_card_id,v_trans_type,v_eqp_id,v_trans_date,v_trans_time,v_trans_amt,v_bak_id;
  end loop;
  close zzy_cursor;
end;

关键步骤说明

1、​​遍历待处理数据​​

通过游标 zzy_cursor 按时间顺序获取本地表 zzy_local_tab 中所有未标记(bz is null)的记录。

​​2、检查远程表匹配​​

对每条记录,通过多字段组合(card_id, trans_type, eqp_id, trans_date, trans_time, trans_amt)查询远程表是否存在相同数据。

​​3、更新本地表状态​​

●若匹配成功(v_exist > 0),从远程表获取匹配记录的 bak_id,并更新本地表的 bz(标记为已处理,避免重复处理)和 bak_id 字段
●若匹配不成功,仅跳过不处理

4、逐行提交事务​​

每次循环后立即执行 COMMIT,确保每条记录的更新独立提交。

图片[2]-在SQL中使用游标从一个表中取值更新另一个表的记录-十一张
© 版权声明
THE END
如果觉得这篇文章对您有帮助,可以收藏本网址,方便下次访问!
点赞16 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容