1)After Triggers
1. Working with INSERT Triggers
INSERT INTO Customers
VALUES ('Mayank','Gupta','Hauz Khas','Delhi',
'Delhi','110016','01126853138')
INSERT INTO Customers
VALUES('Himanshu','Khatri','ShahjahanMahal ',
'Jaipur','Rajesthan','326541','9412658745')
INSERT INTO Customers
VALUES ('Sarfaraz','Khan','Green Market',
'Hydrabad','AP','698542','9865478521')
INSERT INTO Products
VALUES ('ASP.Net Microsoft Press',550)
INSERT INTO Products
VALUES ('ASP.Net Wrox Publication',435)
INSERT INTO Products
VALUES ('ASP.Net Unleased',320)
INSERT INTO Products
VALUES ('ASP.Net aPress',450)
CREATE TRIGGER invUpdate ON [Orders]
FOR INSERT
AS
UPDATE p SET p.instock=[p.instock - i.qty]
FROM products p JOIN inserted I ON p.prodid = i.prodid
2.Working with DELETE Triggers
CREATE TRIGGER DelhiDel ON [Customers]
FOR DELETE
AS
IF (SELECT state FROM deleted) = 'Delhi'
BEGIN
PRINT 'Can not remove customers from Delhi'
PRINT 'Transaction has been canceled'
ROOLBACK
END
3.Working with UPDATE Triggers
CREATE TRIGGER CheckStock ON [Products]
FOR UPDATE
AS
IF (SELECT InStock FROM inserted) < 0
BEGIN
PRINT 'Cannot oversell Products'
PRINT 'Transaction has been cancelled'
ROLLBACK
END
2.Multiple After Triggers
If you are using multiple triggers, it is of course essential to know which order they fire in.If you want more than two triggers to fire in a specific order, there is no way to specifically define this. A deeply unscientific test I did indicated that multiple triggers for the same table and operation will run in the order they were created unless you specifically tell them otherwise.
3.Instead Of Triggers
Instead Of Triggers fire instead of the operation that fires the trigger, so if you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, they will not actually get deleted (unless you issue another delete instruction from within the trigger) as in this simple example:
CREATE TABLE Mayank (Name varchar(32))
GO
CREATE TRIGGER tr_mayank ON Mayank
INSTEAD OF DELETE
AS
PRINT 'Sorry - you cannot delete this data'
GO
INSERT Mayank
SELECT 'Cannot' union
SELECT 'Delete' union
SELECT 'Me'
GO
DELETE Mayank
GO
SELECT * FROM Mayank
GO
DROP TABLE Mayank
1) You can define an Instead Of trigger on a view (something that will not work with After triggers) and this is the basis of the Distributed Partitioned Views that are used so split data across a cluster of SQL Servers.
2) You can use Instead Of triggers to simplify the process of updating multiple tables for application developers.
3)Mixing Trigger Types.
Rajasekhar0544, if this helps please login to Mark As Answer. | Alert Moderator