存储过程执行删除重复数据、动态执行sql、拼接sql

今天客户提了一个需求,需要处理下用户我的产品重复数据,是根据产品名称和产品编码、规格型号等字段判断是否有重复数据,如果有重复数据,删除多余的重复数据只保留一个即可;对应的写了一个存储过程:

这里用到了游标和sql拼接及动态执行sql等部分

create or replace procedure test is
    -- 条件sql
    vc_sql varchar2(4000);  
    --临时sql
    vc_tempSql varchar2(4000); 
    --删除sql 主要执行的sql 
    vc_deleteSql varchar(4000) ; 
    --计算sql,主要用于计算有几条重复数据 
    vc_selectSql varchar(4000) ;
    --接收vc_selectSql计算的结果
    vc_count number;  
   --spfl表游标定义
  cursor a_spfl is
  select * from test_table t where t.validate_flag = 1 and t.user_id is not null and t.nsrsbh is not null;
 
begin
  --vc_sql :='select * from test_table a where  a.validate_flag = 1'; 
    
  for a in a_spfl loop
     vc_deleteSql :='delete from  test_table t  where  t.validate_flag = 1 ';
     vc_selectSql :='select count(1) from  test_table t  where  t.validate_flag = 1 ';
     vc_tempSql :=' and t.id = '''||a.id||'''';
   --  vc_sql := ' and t.user_id = '||a.user_id||' and t.nsrsbh ='''||a.nsrsbh||'''' ;
     --用户id
      if a.user_id is null  then
        vc_sql := '';
       else
       vc_sql := ' and t.user_id = '||a.user_id||' and t.nsrsbh ='''||a.nsrsbh||'''' ;
     end if;
      --nsrsbh
      if a.nsrsbh is null  then
         vc_sql := vc_sql;
       else
       vc_sql :=vc_sql ||' and t.nsrsbh ='''||a.nsrsbh||'''' ;
     end if;
     --产品名称
     if a.product_name is null  then
       vc_sql := vc_sql ||' and t.product_name is null';
     else
        vc_sql := vc_sql ||' and t.product_name ='''||a.product_name||'''' ;
     end if;
     --价格
     if a.price is null then
       vc_sql := vc_sql ||' and t.price is null';
     else
        vc_sql := vc_sql ||' and t.price ='''||a.price||'''' ;
     end if;
     --product_category_code 税收分类编码
     if a.product_category_code is null then
       vc_sql := vc_sql ||' and t.product_category_code is null';
     else
        vc_sql := vc_sql ||' and t.product_category_code ='''||a.product_category_code||'''' ;
     end if;
     
      --规格型号
     if a.specification is null then
       vc_sql := vc_sql ||' and t.specification is null';
     else
        vc_sql := vc_sql ||' and t.specification ='''||a.specification||'''' ;
     end if;
     --拼接删除sql
     vc_deleteSql := vc_deleteSql || vc_tempSql || vc_sql;
     --拼接计数sql
     vc_selectSql := vc_selectSql || vc_sql;
    ---  dbms_output.put_line(vc_selectSql);
     ---执行计数sql并且把查询出的数量赋值给vc_count
      execute immediate vc_selectSql into vc_count;  
      --如果计算大于2说明有重复数据         
      if vc_count >1 then
        --执行删除sql
        execute immediate vc_deleteSql ;
         commit;
        else
          vc_count := 0;
      end if;                


  end loop;
end;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值