场景
向一个数据库表中插入数据行,只有当要插入的数据行不存在时,才插入。插入时,需要保证一定不能向数据表中插入重复的数据行。
数据库表 names:
create table names(
id int identity(1,1) not null,
name varchar(10) not null
)
names表中已有的数据行
id name
1 zhangsan
2 meinv
实现
1 利用INSERT INTO ...SELECT 语句的原子性
declare varchar(10) ;
set @name='zhangsan';
insert into names select where not exists (select 1 from names where name=)
2 利用MERGE语句
declare varchar(10) ; set @name='zhangsan'; MERGE namesAS target USING (SELECT @Name) AS source ( Name) ON (target.name = source.name) WHEN NOT MATCHED THEN INSERT (Name) VALUES (source.Name);