不会重复插入

1 创建测试表

create table T_20211111
(
Id int,
Score decimal(10,2)
);

2.1 MySql 不重复插入语句

使用 dual 保证 Id 不重复插入到表中

insert into T_20211111(Id,Score)
select 1,12.23
from dual
where not exists
(
select 1 from T_20211111 where Id=1
)

使用 replace into 保证不重复插入到表中

-- Id 列为主键列,通过主键列来判重,如果没用主键列会重复插入
replace into T_20211111(Id,Score)
values(1,10.22),(1,10.22),(1,10.22);

2.2 SqlServer 不重复插入语句

保证 Id 不重复插入到表中

insert into T_20211111(Id,Score)
select 1,12.23
where not exists
(
select 1 from T_20211111 where Id=1
)

 3 也可以在表上加上唯一索引,然后插入代码对于因为唯一索引导致的插入异常使用 try-catch 包裹。

posted @ 2021-11-11 22:14  温故纳新  阅读(42)  评论(0编辑  收藏  举报