SQL insert 主键冲突

待总结

  1. https://blog.csdn.net/JavaCoder_juejue/article/details/82313891
  2. https://blog.csdn.net/a772304419/article/details/79669614 插入前,判断存不存在
  3. 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
posted @ 2019-05-04 22:47  Mouer404  阅读(658)  评论(0编辑  收藏  举报