系统功能背后的逻辑——更新并插入
更新并插入的自动实现功能:
思路是写一个函数,先按条件查询数据,如果查询到数据则更新,如果没有查询到数据则插入:
create or replace function fn_merge_index(statdate in date,
cpid in varchar2,
indextypecode in number,
indexitemcode in number,
indexdata in varchar2)
return number is
numb number;
begin
select count(*)
into numb
from cp_index_statistics_rec
where stat_date = to_date(to_char(statdate, ‘yyyy/mm/dd’), ‘yyyy/mm/dd’)
and cp_id = cpid
and index_type_code = indextypecode
and index_item_code = indexitemcode;
if numb = 0 then
–数据不存在,insert
begin
insert into cp_index_statistics_rec
(stat_id,
stat_date,
diagnosis,
cp_id,
is_validate,
index_type_code,
index_item_code,
stat_data,
stat_create_date,
cp_name)
values
(cp_index_statistics_rec_seq.nextval,
to_date(to_char(statdate, ‘yyyy/mm/dd’), ‘yyyy/mm/dd’),
‘’,
cpid,
1,
indextypecode,
indexitemcode,
indexdata,
(select sysdate from dual),
(select cp_name from cp_templet_master where cp_id = cpid));
commit;
end;
else
–数据存在,update
begin
update cp_index_statistics_rec
set is_validate = 1,
stat_data = indexdata,
stat_create_date =
(select sysdate from dual)
where stat_date = to_date(to_char(statdate, ‘yyyy/mm/dd’), ‘yyyy/mm/dd’)
and cp_id = cpid
and index_type_code = indextypecode
and index_item_code = indexitemcode;
commit;
end;
end if;
return numb;
end fn_merge_index;
注意to_date(to_char(statdate, ‘yyyy/mm/dd’), ‘yyyy/mm/dd’)这个写法,如果写成to_date(statdate, ‘yyyy/mm/dd’),根据NLS不同,可能导致数据出错。具体请看这里
另外oracle提供了merge into可以实现此功能,理论上讲比上面的效率会高,但是没做试验。merge into有个缺点就是在10g以下版本的oracle中会出现问题,导致比较严重的后果(据说会把所有的数据都更新,而9i又不支持在update后加条件),所以我没有采用这个方法。
merge into的用法:
merge into bonuses d
using (select employee_id, salary, department_id from employees
where department_id = 80) s
on (d.employee_id = s.employee_id)
when matched then update set d.bonus = d.bonus + s.salary*.01
when not matched then insert (d.employee_id, d.bonus)
values (s.employee_id, s.salary*0.01);
附链接:
https://blog.csdn.net/weixin_39734304/article/details/79182416
另外还有个思路,直接update,执行后会返回受影响的行数,如果行数为0,表示没有符合条件的数据,后面执行insert;如果行数大于0,表示有符合条件的行数且update执行成功
- GridView实现 "插入" 编辑更新删除功能
- sqlserver 插入或更新表常用 系统错误消息 整理
- 社交开源系统ThinkSNS V4.6.4更新,版本更新提示功能上线
- 模块管理常规功能自己定义系统的设计与实现(52--功能更新[2] 对百分比字段的操作)
- 201402 系统更新后 VS2010 的宏功能不能正常使用(如添加头注释)
- ASP.NET实现增删改查等功能(Access版)系统之五-更新
- 逻辑思考之选择限定范围内的数量插入不指定位置并且具有替换功能
- 机房收费系统之逻辑功能
- 系统设计 - IOS 程序插件及功能动态更新思路
- 一步一步实现web程序信息管理系统之三----登陆业务逻辑实现(验证码功能+参数获取)
- yum功能:安装软件组,全系统更新
- 心愿作品——图片搜索系统(功能可用了,下一步布置到公网。笔记更新...)
- LINQ下使用三层架构的探索(五)逻辑访问层中的带参查询、插入、更新以及删除。
- 模块管理常规功能自定义系统的设计与实现(54--视频讲解更新高清 )
- php 连接mysql数据库,查询、插入、更新、删除功能
- 安全远程更新扩展嵌入式系统功能和生命周期
- 模块管理常规功能自定义系统的设计与实现(51--功能更新[1] 对父模块的链接显示)
- Android系统更新防互刷功能实现与分析
- 在 mysql 中利用 Duplicate key, 一句话实现存在的更新不存在插入功能
- 在系统中插入视频聊天的功能