插入数据,已存在则不插入

--如果数据已经存在,请忽略
if not exists(select 1 from A where ID = 9)
begin
    insert into A values('d123')
end

if (select 1 from A where ID = 9) is null
begin
    insert into A values('d123')
    insert into A values('d123')
end
exists用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回值True或False
exists指定一个子查询,检测 行 的存在。

语法: EXISTS subquery
参数: subquery 是一个受限的 SELECT 语句 (不允许有 COMPUTE 子句和 INTO 关键字)。
结果类型: Boolean 如果子查询包含行,则返回 TRUE ,否则返回 FLASE 。

猜你喜欢

转载自www.cnblogs.com/Cengjianwei/p/10749724.html