插入时判断是否有重复值的sql怎么写

liquidcn 2009-01-03 10:41:38
我有一张表tab,有两个字段a,b,c(a是自动增加的)

当我插入一个新值的时候想判断字段b是否有重复,如果有重复就做更新操作

比如:
a b c
1 f1 uuu
2 f2 ooo
3 f3 ttt

插入时判断b列的值是否重复,重复则做更新操作:

插入数据为f3 iii时,就会执行更新操作,将f3原先的值替换为iii

插入f4 jjj就正常插入

存储过程该怎么写比较高效,因为数据量比较大
...全文
1163 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
WOFEIYANG 2009-01-04
  • 打赏
  • 举报
回复
实际上UPDATE触发器的工作原理是删除原表后从inserted表中获取数据插入原表。
WOFEIYANG 2009-01-04
  • 打赏
  • 举报
回复
实际上UPDATE触发器的工作原理是删除原表后从inserted表中删除数据。

因此楼主应该可以这样做:

create trigger checktab on tab instead of insert,update as

delete from a where a.col in (select col from inserted)

insert into a select * from inserted
tchey 2009-01-04
  • 打赏
  • 举报
回复
create trigger checktab on tab instead of insert,update as
if(select count(b) from inserted)>0
begin
update tab set tab.c=inserted.c from tab,inserted
where tab.b=inserted.b;
end;
insert into tab values('f3','iii');
yuxianye1 2009-01-04
  • 打赏
  • 举报
回复
这个问题偶是用存储过程做的,看了楼上的触发器方法也很好。至于效率方面那个更好 偶没有测试过。
worlddba 2009-01-04
  • 打赏
  • 举报
回复
楼上的很强大
linguojin11 2009-01-04
  • 打赏
  • 举报
回复
楼上的大哥都对的。。没得说了
dawugui 2009-01-04
  • 打赏
  • 举报
回复
[Quote=引用楼主 liquidcn 的帖子:]
我有一张表tab,有两个字段a,b,c(a是自动增加的)

当我插入一个新值的时候想判断字段b是否有重复,如果有重复就做更新操作

比如:
a b c
1 f1 uuu
2 f2 ooo
3 f3 ttt

插入时判断b列的值是否重复,重复则做更新操作:

插入数据为f3 iii时,就会执行更新操作,将f3原先的值替换为iii

插入f4 jjj就正常插入

存储过程该怎么写比较高效,因为数据量比较大
[/Quote]
if not exists(select 1 from tb where b = 某变量)
insert into tb ...
else
update tb set ....
百年树人 2009-01-03
  • 打赏
  • 举报
回复
刚才的有点问题

---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([a] int identity(1,1),[b] varchar(2),[c] varchar(3))
insert [tb]
select 'f1','uuu' union all
select 'f2','ooo' union all
select 'f3','ttt'

---创建触发器---
create trigger tri_tb
on tb
instead of insert
as
begin
if exists(select 1 from inserted i,tb t where i.b=t.b)
update tb set tb.c=i.c from inserted i where tb.b=i.b
else
insert tb select b,c from inserted
end

---插入---
insert into tb values('f3','iii')
insert into tb values('f4','jjj')

---查询---
select * from [tb]

---结果---
a b c
----------- ---- ----
1 f1 uuu
2 f2 ooo
3 f3 iii
4 f4 jjj

(4 行受影响)
百年树人 2009-01-03
  • 打赏
  • 举报
回复
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([a] int identity(1,1),[b] varchar(2),[c] varchar(3))
insert [tb]
select 'f1','uuu' union all
select 'f2','ooo' union all
select 'f3','ttt'

---创建触发器---
create trigger tri_tb
on tb
instead of insert
as
begin
if exists(select 1 from inserted i,tb t where i.b=t.b)
update tb set tb.c=i.c from inserted i where tb.b=i.b
end

---插入---
insert into tb values('f3','iii')

---查询---
select * from [tb]

---结果---
a b c
----------- ---- ----
1 f1 uuu
2 f2 ooo
3 f3 iii

(3 行受影响)
百年树人 2009-01-03
  • 打赏
  • 举报
回复
触发器?

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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