Say I have a self relation table as following :
ID - Name - ParentID
Now everytime that users insert sth in this table I would like to check if the Name inserted is already in the
rows where ParentID equals to the inserted one , if true then rollback the transaction.
But the problem is when I check the rows with the parentID from the inserted table the inserted row is already in the main table too. So, the trigger always rolls back the transaction.
Here is my trigger :
ALTER TRIGGER TG_Check_Existance_In_myTbl
ON myTbl FOR INSERT,UPDATE AS
DEClARE @result BIT
DECLARE @numberOfRows INT
DECLARE @counter INT
DECLARE @names nVARCHAR (30)
DECLARE @name NVARCHAR (30)
SET @result = 0
SET @numberOfRows = (SELECT COUNT (Name)
FROM myTbl
WHERE ParentID IN
(
SELECT ParentID
FROM inserted
)
)
SET @counter = 1;
SELECT @name = Name
FROM inserted
WHILE (@counter <= @numberOfRows)
BEGIN
WITH Q
AS
(
SELECT ROW_NUMBER()
OVER (ORDER BY Name) 'Row', Name
FROM myTbl WHERE ParentID IN
(
SELECT ParentID
FROM inserted
)
)
SELECT @names = Name
FROM Q
WHERE Row = @counter
IF @name = @names
SET @result=1;
SET @counter = @counter + 1
END
IF @result = 1
ROLLBACK TRAN
Unless I am missing something you are making this way too hard.
Why don’t you use a unique constraint on the two columns?
table_constraint (Transact-SQL)