先判断记录是否存在,不存在则将记录插入表的sql语句

以前都分两步,先判断记录数: select count(*) 如果值等于0则表示不存在,然后再插入数据。其实可以用insert ...select一条sql语句完成。

例子1:

insert into User(Name)
select   “张三”
where not exists(select UserId from User where Name="张三")

例子2:

insert into task_fav(taskid,opid,opdate)
select @taskid,@opid,getdate()
where not exists (select taskid from task_fav where taskid=@taskid andopid=@opid)

例子3:

insert into tbTeam_daily
select N'2011-12-2',N'3組',N'',N'23'
WHERE not exists (select * from tbTeam_daily where tdate = N'2011-12-2' and teamName = N'4組')

你可能感兴趣的:(SQLServer)