I use this code to check if an element of the new entry is equal to an element of previously inserted data.
CREATE TRIGGER trig1 ON Table1
AFTER INSERT
AS
DECLARE trigcursor CURSOR FOR
SELECT Name FROM INSERTED
DECLARE @Name1 varchar(80)
OPEN trigcursor;
FETCH NEXT FROM trigcursor INTO @Name1
WHILE @@FETCH_STATUS = 0
BEGIN
IF EXISTS(SELECT * FROM Table1 WHERE Name= @Name1)
BEGIN
...
END
FETCH NEXT FROM trigcursor INTO @Name1
END
The problem is that for some reason the new entry exists also in the table Table1, not only in INSERTED. So the condition is always true. Can you help me why this happens? Is there a way to retrieve only the initial table without the new entry in it? Thanks!
Your trigger is
AFTER INSERTon tableTable1. It should beBEFORE INSERTif you expect not to find the record in the table.Alternative: use INSTEAD OF INSERT trigger.
OR
Add another column that accepts null. Make it a number column so that it will be fast. Do not insert any value in it on the insert. Then, in the AFTER INSERT TRIGGER, the rows that have that column empty are the new ones. The ones that have the column filled with something are the old ones.
Then update empty columns with value.
eg: add column
markAfter insert, look for the name:
Once you found out whether or not it existed before, update everything with something: