I have a table with a AutoIdentity column as its PK and a nvarchar column called “IdentificationCode”. All I want is when inserting a new row, it will search the table for any preexisting IdentificationCode, and if any found roll back the transaction.
I have written the folowing trigger:
ALTER trigger [dbo].[Disallow_Duplicate_Ids]
on [dbo].[tbl1]
for insert
as
if ((select COUNT(*) from dbo.tbl1 e , inserted i where e.IdentificationNo = i.IdentificationNo ) > 0)
begin
RAISERROR('Multiple Ids detected',16,1)
ROLLBACK TRANSACTION
end
But when inserting new rows, it always triggers the rollback even if there is no such IdentificationCode.
Can any one help me please?
thanks
As @Qpirate mentions, you should probably put some sort of
UNIQUEconstraint on the column. This is probably ‘stronger’ than using a trigger, as there’s ways to disable those.Also, the implicit-join syntax (comma-separated
FROMclause) is considered an SQL anti-pattern – if possible, please always explicitly declare your joins.I suspect that your error is because your trigger seems to be an
AFTERtrigger, and you check to see if there are any (non-zero) rows in the table; in other words, the trigger is (possibly) ‘failing’ theINSERTbecause it wasINSERTed. Changing it to aBEFORE(orINSTEAD OF) trigger, or changing the count to>= 2may solve the problem.Without seeing your insert statement, it’s impossible to know for sure, but (especially if you’re using a SP), you may be able to check for existence in the
INSERTstatement itself, and throw an error (or do something else) if the row isn’t inserted.For example, the following:
Will return a code indicating ‘row not found’ (inserted, etc; on pretty much every system this is
SQLCODE = 100) ifidentificationCodeis already present.