Monday, March 26, 2012

Duplicate record trigger

This is part of my trigger on table T1. I am trying to check if the records inserted to T1 is available in myDB.dbo.myTable or not (destination table). If it is available rollback T1. It does not do that although I insert the same records twice.

-- duplicate record check

SET @.step = 'Duplicate record'

IF EXISTS (

SELECT i.myID, i.Type

FROM INSERTED i INNER JOIN

myDB.dbo.myTable c ON i.myID = c.myID

GROUP BY i.myID, i.Type

HAVING (COUNT(*) > 1) AND (i.Type = 'In')

)

BEGIN

ROLLBACK transaction

RAISERROR('Error: step: %s. rollback is done.', 16, 1, @.step)

Return

END

What is problem?

You may not use the SET statement and I also did not see an aggregate function with your GROUP BY which means it is not a GROUP BY but a standard DISTINCT. The link below covers what you need to know and a sample of what you can do in SQL Server. Hope this helps.

http://www.sommarskog.se/error-handling-I.html

No comments:

Post a Comment