I have a process that allows users to insert data from Excel file into a single SQL Server table using VBA. Multiple users can insert data concurrently as they use the file independently from their workstations.
The SQL script from Excel creates one insert into
statement only, so everything is inserted as a batch (presumably) by each user.
For example:
INSERT INTO TABLE (col1, col2)
VALUES (a,b), (c,d), (e,f);
I wrote an After Insert
trigger on the table as follows to be able to identify & generate a unique ID for each batch (plus an 'extraID' for downstream purposes). Given the locks used, is it possible for the batch ID to be not unique given concurrent usage from the Excel files?
Could you recommend changes to ensure so if not? Thanks!
CREATE TRIGGER [dbo].[example]
ON [dbo].[tblExample]
INSTEAD OF INSERT
AS
BEGIN
BEGIN TRANSACTION;
DECLARE @batchID AS int
DECLARE @extraID AS int
SELECT @batchID = COALESCE(MAX(BatchID), 0) + 1
FROM tblExample WITH (TABLOCKX, HOLDLOCK)
SELECT @extraID = COALESCE(MAX(nodeID), 0) + 1
FROM tblExample WITH (TABLOCKX, HOLDLOCK)
INSERT INTO [tblExample] WITH (TABLOCK)
SELECT @batchID, @extraID, col1, col2
FROM inserted
COMMIT TRANSACTION;
END
1条答案
按热度按时间f4t66c6m1#
Like I mentioned in the comments, I would suggest using a
SEQUENCE
; there's no need to "reinvent the wheel" here.The above
SELECT
returns the following: