SQL insert 主键冲突
待总结
- https://blog.csdn.net/JavaCoder_juejue/article/details/82313891
- https://blog.csdn.net/a772304419/article/details/79669614 插入前,判断存不存在
- https://www.cnblogs.com/luffe/p/7865316.html
1.
----------- 测试表及数据 ----------------
USE tempdb
GO
IF OBJECT_ID('A') IS NOT NULL DROP TABLE A
GO
CREATE TABLE A(
sno INT NOT NULL PRIMARY KEY
,[name] NVARCHAR(10)
,remark NVARCHAR(10)
,times INT
)
GO
INSERT INTO A(sno,[name],remark) VALUES(2,'2n','2nremark')
----------- 执行测试的并发代码 -----------
BEGIN TRAN
IF NOT EXISTS(SELECT * FROM A WITH(ROWLOCK,XLOCK) WHERE sno=1)
INSERT INTO A VALUES (1,'test1','ceshi',0)
ELSE
UPDATE A SET remark='ceshi',times=times+1 WHERE sno=1
COMMIT TRAN;
2.
begin tran
update A set reamark = '测试' where sno = 1 and name = 'test'
if @@ROWCOUNT = 0
begin
insert into A values (1,'test','测试')
end
commit