Here is my trigger:
ALTER TRIGGER DONORINFO_INSERT
ON [dbo].[DONORINFO] INSTEAD OF INSERT
AS
DECLARE @sequence AS VARCHAR(50) = ''
DECLARE @tranLen VARCHAR(10)
SET @sequence = (SELECT TOP 1 SUBSTRING([DONORID], 3, 8)
FROM [dbo].[DONORINFO]
ORDER BY [DONORID] DESC)
IF (@sequence IS NULL OR @sequence = '')
BEGIN
SELECT @sequence = REPLICATE('0', 7 ) + '1'
END
ELSE
BEGIN
SELECT @tranLen = LEN(@sequence)
SELECT @sequence = @sequence + 1
SELECT @tranLen = ABS(@tranLen - LEN(CAST(@sequence AS INT)))
SELECT @sequence = REPLICATE('0', @tranLen) + @sequence
END
DECLARE @DONORID AS [nvarchar](50) = 'DN' + CONVERT(VARCHAR, @sequence)
INSERT INTO [dbo].[DONORINFO] ([DONORID], [DONORNAME])
SELECT @DONORID, inserted.DONORNAME
FROM inserted
In the first lines of the script, I'm reading the DONORINFO
table in which I checked if the unique id exists. After that, I will insert the record into that table. I tested the first time, the insert into select script works but for the second time around, it fails and sends and a violation of primary key error.
But if I tested row by row insert, it works.
This is the row by row insert script that works.
INSERT INTO [dbo].[DONORINFO] ([DONORID], [DONORNAME])
VALUES ('DN00000001', 'test')
If I run it twice, the records will be like this:
DONORID DONORNAME
---------------------
DN00000001 test
DN00000002 test
This is the insert into select script that doesn't work:
INSERT INTO [dbo].[DONORINFO] ([DONORID], [DONORNAME])
SELECT
'',
[NameOfDonor]
FROM
[dbo].[_TEMPENDOWMENTFUND] AS ENDF
WHERE
[ENDF].[NameOfDonor] NOT IN (SELECT [DONORNAME]
FROM [dbo].[DONORINFO])
The _TEMPDOWMENTFUND
is a table I created that will store the data that was migrated from an Excel worksheet, the purpose of the trigger is that it will generate a unique DONORID
for every record inserted on the DONORINFO
table.
Now my problem is that, I want to perform the insert into select statement which is a multiple row insert, but I'm having a hard time figuring out what is going wrong to the trigger I created.
Any help would be appreciated. Thanks.