34,590
社区成员
发帖
与我相关
我的任务
分享
-- 或者使用 merge 语法也可以的
create table test(phone varchar(10))
go
create unique index ix_test on test(phone)
go
print '-- 第一次写入'
merge into test
using (select '110' c ) c on test.phone = c.c
when not matched then
insert (phone) values(c.c);
select @@ROWCOUNT c
go
print '-- 第二次写入'
merge into test
using (select '110' c ) c on test.phone = c.c
when not matched then
insert (phone) values(c.c);
select @@ROWCOUNT c
go
select * from test
go
drop table test
go
-- 第一次写入
(1 行受影响)
c
-----------
1
(1 行受影响)
-- 第二次写入
(0 行受影响)
c
-----------
0
(1 行受影响)
phone
----------
110
(1 行受影响)
create table test(phone varchar(10))
go
create unique index ix_test on test(phone)
go
print '-- 第一次写入'
insert into test(phone)
select '110'
where not exists(select * from test where phone = '110')
select @@ROWCOUNT c
go
print '-- 第二次写入'
insert into test(phone)
select '110'
where not exists(select * from test where phone = '110')
select @@ROWCOUNT c
go
select * from test
go
drop table test
go
-- 第一次写入
(1 行受影响)
c
-----------
1
(1 行受影响)
-- 第二次写入
(0 行受影响)
c
-----------
0
(1 行受影响)
phone
----------
110
(1 行受影响)