1

I have a problem with a situation when many users insert a record to the database in the same time and in column scope_id there are duplicated values. Is there a way to protect duplication of value?

@scope_id = SCOPE_IDENTITY()

I thought about a trigger but maybe is a simpler solution.(Checking before that id is in the database doesn't always work.)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Prezes Łukasz
  • 938
  • 1
  • 9
  • 30

2 Answers2

2

If you are using SQL Server 12+ I would suggest to take advantage of the SEQUENCE object (MSDN reference).

Sample code from the above reference:

Creating the sequence:

CREATE SEQUENCE Test.CountBy1  
    START WITH 1  
    INCREMENT BY 1 ;  
GO  

Using it:

DECLARE @NextID int ;  
SET @NextID = NEXT VALUE FOR Test.CountBy1;  
-- Some work happens  
INSERT Test.Orders (OrderID, Name, Qty)  
    VALUES (@NextID, 'Rim', 2) ;  
GO 

The NEXT VALUE statement consumes the next value of the sequence before even trying to insert a record.

Giorgos Altanis
  • 2,742
  • 1
  • 13
  • 14
  • I should say this `-- Some work happens` looks scary . They'd better say `-- Some cautiously programmed work happens`. – Serg Mar 02 '17 at 08:33
1

what you are looking for can be achieved by using the T-SQL functions NEWSEQUENTIALID. This generates sequential global unique identifiers to be stored in an attribute of a UNIQUEIDENTIFIER type. The GUIDs are guaranteed to be unique across space and time

It can be used at the time of declaring the table as well For example:

CREATE TABLE myTable (ColumnA uniqueidentifier DEFAULT NEWSEQUENTIALID())
DK5
  • 317
  • 3
  • 15