oracle数据库存储过程,一个关于存在则跳过,不存在则新增的问题

2025-03-13 19:01:11
推荐回答(1个)
回答1:

表结构就是你给的,我添了点数据

insert into a values (1,to_date('2014-03-01','yyyy-mm-dd'),1);
insert into a values (2,to_date('2014-03-03','yyyy-mm-dd'),1);
insert into a values (3,to_date('2014-03-04','yyyy-mm-dd'),1);
insert into a values (4,to_date('2014-03-05','yyyy-mm-dd'),1);
insert into a values (5,to_date('2014-03-06','yyyy-mm-dd'),1);
insert into a values (6,to_date('2014-03-07','yyyy-mm-dd'),1);
insert into a values (7,to_date('2014-03-08','yyyy-mm-dd'),1);

存储过程

create or replace procedure p_insert(v_userid     varchar2,
                                     v_begin_date varchar2,
                                     v_end_date   varchar2) as
  v_val   int;
  v_count int;
  cursor c_cur is
    select rownum - 1
      from dual
    connect by rownum <= (select to_date(v_end_date, 'yyyy-mm-dd') -
                                 to_date(v_begin_date, 'yyyy-mm-dd') + 1
                            from dual);
begin
  open c_cur;
  loop
    fetch c_cur
      into v_val;
    exit when c_cur%notfound;
    select count(*)
      into v_count
      from A
     where val_date = to_date(v_begin_date, 'yyyy-mm-dd') + v_val
       and userid = v_userid;
    if v_count = 0 then
      insert into A
      values
        (1, to_date(v_begin_date, 'yyyy-mm-dd') + v_val, v_userid);--这个地方我把ID写死了,我都写成1了,不过我想你那个实际的里应该有序列或触发器来着
      commit;
    end if;
  end loop;
  close c_cur;
end;

执行


begin
  p_insert(1,'2014-03-01','2014-03-10');--日期必须以这种格式输入,不过你可以在存储过程里改成你想要的格式
end;

结果自己检测吧,我这没问题