本文介绍了防止插入时出现重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个表使用标识列作为其主键和两个 列(为简单而减少表)EmployeeNumber和ArrivalTime。 CREATE TABLE [tblRecords]( [ID] [bigint] IDENTITY(1,1)NOT NULL, [EmployeeNumber] [varchar](10)COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [ArrivalTime] [datetime] NOT NULL, CONSTRAINT [PK_tblRecords] PRIMARY KEY CLUSTERED ( [ID] )ON [PRIMARY] )ON [PRIMARY] GO 我有一个插入程序,在插入之前检查重复项 a新记录: IF(SELECT TOP 1 [ID] FROM tblRecords WHERE EmployeeNumber = @SocialSecurity)IS NULL BEGIN INSERT INTO tblRecords(EmployeeNumber,ArrivalTime) VALUES (@EmployeeNumber,@ ArrivalTime) SELECT SCOPE_IDENTITY() END ELSE SELECT 0 AS DuplicateRecord 在99.9%的情况下,这很有效。但是,如果 插入尝试的字面意思是滴答。除此之外,SELECT TOP 1 ... 命令在第一次尝试完成之前完成两次尝试。 所以如果程序我最终会有重复的条目被称为多次 倍迅速。系统需要在过去45天内防止重复 EmployeeNumbers,因此将EmployeeNumber 设置为UNIQUE将不起作用。我可以很容易地查看较旧的条目(45天或 更新),但我不知道如何处理在毫秒内多次调用 过程的时间。在这种情况下使用ROLLBACK 进行INSERT后,是否会带有重复检查的 TRANSACTION?非常感谢任何帮助! -EI have a table using an identity column as its Primary Key and twocolumns (table reduced for simplicity) EmployeeNumber and ArrivalTime.CREATE TABLE [tblRecords] ([ID] [bigint] IDENTITY (1, 1) NOT NULL ,[EmployeeNumber] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_ASNOT NULL ,[ArrivalTime] [datetime] NOT NULL ,CONSTRAINT [PK_tblRecords] PRIMARY KEY CLUSTERED([ID]) ON [PRIMARY]) ON [PRIMARY]GOI have an insert procedure that checks for duplicates before insertinga new record:IF (SELECT TOP 1 [ID] FROM tblRecords WHERE EmployeeNumber =@SocialSecurity) IS NULLBEGININSERT INTO tblRecords(EmployeeNumber,ArrivalTime)VALUES (@EmployeeNumber, @ArrivalTime)SELECT SCOPE_IDENTITY()ENDELSESELECT 0 AS DuplicateRecordIn 99.9% of the cases, this works well. However, in the event that theinsert attempts are literally "ticks" apart, the "SELECT TOP 1..."command completes on both attempts before the first attempt completes.So I end up with duplicate entries if the procedure is called multipletimes vey quickly. The system needs to prevent duplicateEmployeeNumbers within the past 45 days so setting the EmployeeNumberto UNIQUE would not work. I can check for older entries (45 days ornewer) very easily, but I do not know how to handle the times when theprocedure is called multiple times within milliseconds. Would aTRANSACTION with a duplicate check after the INSERT with a ROLLBACKwork in this case? Any help is greatly appreciated!-E推荐答案 这里需要可序列化的隔离级别。我认为SELECT语句中的UPDLOCK 是最好的。 (使用普通HOLDLOCK你可以 陷入僵局。) 至于触发器是否最好......你不必失眠结束 并发插入,但如果出现错误,你可以做更多工作(INSERT + ROLLBACK)。是否需要错误消息我们不知道。再说一遍, 你可以同时拥有两者。强制执行业务规则的触发器,以及 应用程序代码,以提供良好的行为。 - Erland Sommarskog ,SQL Server MVP, es****@sommarskog.se 联机丛书适用于SQL Server SP3 http:/ /www.microsoft.com/sql/techinf...2000/books.asp 这篇关于防止插入时出现重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-29 08:53