I have a table as follows:
CREATE TABLE [Alg].[Sequence](
[Id] [int] IDENTITY(1,1) NOT NULL,
[SequenceId] [int] NOT NULL,
[CustomerId] [bigint] NOT NULL,
[Data] [text] NULL,
CONSTRAINT [PK_Sequence] PRIMARY KEY CLUSTERED
(
[SequenceId] ASC,
[CustomerId] ASC
)
And this is a block from insert/update trigger of another table where I insert data to Sequence
table:
--insert data into sequence table
SELECT @MaxSeqId = ISNULL(MAX(SequenceId),0)
FROM Alg.[Sequence] WITH (ROWLOCK)
WHERE CustomerId = @CustomerId
INSERT INTO Alg.[Sequence]
VALUES (
@MaxSeqId + 1
,@CustomerId
,@SendingData
,GETDATE()
)
So whenever high frequency insertion processes (on the table with trigger), violation of duplicate key error occurs. I tried ROWLOCK
, but didn't work. How can I prevent this from happenning?
Update
I have been asked why I am not using built-in sequence, I tried but couldn't find how to use sequence with composite primary key. I don't want the SequenceId column be identity, in fact, I would like to keep SequenceId as identity for each CustomerId. You can see my another question related with this