选择insert 还是update,或者结合一起用?

ovisa 2003-12-13 03:11:20
我的表里已经有一个记录,
id=1, name='a',total=2
现在我又有一条记录过来,新记录的name如果等于'a',我会把total的值更新
如果不同就要插入新的记录
id=2 ,name='XXx',total=10

现在我得方法是查询有没有name='a'的记录,如果有就update 没有就insert,这是一种笨的方法.请教一下有没有一个sql语句可以一步到位就完成的?
...全文
264 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2003-12-13
  • 打赏
  • 举报
回复
--不好意思,开始没注意,你的是ACCESS,那不能用触发器,程序中可以这样处理.

--VB为例,注意,你的id字段是自增字段

dim db as adodb.connection
dim re&,sql$,name$,total&

set db=new adodb.connection
db.open 你的数据库连接字符串

'你要插入的值
name="aa"
total=10

'数据插入处理
sql="update 你的表 set total=total+" & total & " where name='" & name & "'"
db.execute sql,re
if re=0 then 're是处理的记录数,如果为0,表示表中没有name,这时进行新增
sql="insert into 你的表(name,total) values('" & name & "'," & total & ")"
db.execute sql,re
end if

zjcxc 2003-12-13
  • 打赏
  • 举报
回复
--下面是例子:

--创建测试表
create table tb(id int identity(1,1),name varchar(10),total int)
go

--创建处理的触发器
create trigger t_insert on tb
instead of insert
as
update tb set total=isnull(a.total,0)+isnull(b.total,0)
from tb a join inserted b on a.name=b.name

insert into tb
select a.name,a.total from inserted a left join tb b on a.name=b.name
where b.name is null
go

--插入数据测试
insert into tb values('aa',2)
insert into tb values('aa',2)
insert into tb values('bb',2)

--显示结果
select * from tb

go
--删除测试表
drop table tb

/*--测试结果
id name total
----------- ---------- -----------
1 aa 4
2 bb 2

(所影响的行数为 2 行)

--*/
zjcxc 2003-12-13
  • 打赏
  • 举报
回复
--用触发器就行了.
--创建处理的触发器
create trigger t_insert on tb
instead of insert
as
update tb set total=isnull(a.total,0)+isnull(b.total,0)
from tb a join inserted b on a.name=b.name

insert into tb
select a.name,a.total from inserted a left join tb b on a.name=b.name
where b.name is null
go
ghosthjt 2003-12-13
  • 打赏
  • 举报
回复
update table1
set ...
where name in (select name from inserted)
insert table1
select * from inserted where name not in (select name from inserted)
changechange 2003-12-13
  • 打赏
  • 举报
回复
jet sql 中没有办法用一句SQL完成你需要的情况,因为涉及到判断等程序流分支,JET SQL是不支持的,所以只能使用你说的方法来达成。

zjcxc(邹建) 的方法和你说的原理一样

7,714

社区成员

发帖
与我相关
我的任务
社区描述
Microsoft Office Access是由微软发布的关系数据库管理系统。它结合了 MicrosoftJet Database Engine 和 图形用户界面两项特点。
社区管理员
  • Access
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧