10/03/2010

Trigger in SQL Server 2005

This trigger check if a Player id is exist or not in another table, if exist this trigger will roll back the transaction and inform an error message. 
IF EXISTS (SELECT name FROM sysobjects
      WHERE name = 'AmaInsert' AND type = 'TR')
   DROP TRIGGER AmaInsert
GO
CREATE TRIGGER AmaInsert
ON Amateur
FOR INSERT
AS
 DECLARE @id int
 SET @id = (SELECT PlayerID from inserted)
IF EXISTS(SELECT * FROM Professional A WHERE A.PlayerID = @id)
BEGIN
 RAISERROR ('This PlayerID %d aldredy exist in table Professional',16,1,@id)
    ROLLBACK TRANSACTION
END

SELECT column_name from inserted mean get the recently inserted value when the trigger fired.

No comments:

Post a Comment

The 0/1 Knapsack Problem - Dynamic Programming

 References: https://www.youtube.com/watch?v=EH6h7WA7sDw  Class Item class Item { private $_weight; private $_value; public functi...