|
|
|
This code demonstrates 1) How to write update trigger which checks modification for a specified field (e.g. here DistrictId) 2) How to handle Errors during update 3) How to update data on linked server. 4) How to do update which requires joining tables 5) How to use XACT_ABORT option to handle transaction so it rolls back all changes if any statement generates run-time error.
Remarks:
When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. When OFF, only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. |
Click here to copy the following block | CREATE TRIGGER tr_PropInfo on its_propertyxref FOR UPDATE AS
SET XACT_ABORT ON
IF exists(select * from inserted) and exists(select * from deleted) begin IF UPDATE(districtid) BEGIN
UPDATE LOKI.PropInfo.dbo.PropInfoXref SET DistrictId=i.DistrictId FROM inserted i JOIN its_propertyxref p ON i.Propid = p.Propid JOIN LOKI.PROPINFO.dbo.PropInfoXref lp ON lp.PropId=i.Propid
If @@error<>0 Begin RAISERROR ('Failed to update LOKI.PropInfo.dbo.PropInfoXref from trigger on PropInfoXref table', 1, 1) ROLLBACK TRAN GOTO lblFail END
UPDATE LOKI.TelecomCorp.dbo.PropInfo SET District_CId=(select District_CID from LOKI.TelecomCorp.dbo.Districtinfo where DistrictId=i.DistrictId) FROM inserted i JOIN its_propertyxref p ON i.Propid = p.Propid JOIN LOKI.TelecomCorp.dbo.PropInfo lp ON lp.PropId=i.Propid
IF @@ERROR<>0 BEGIN RAISERROR ('Failed to update LOKI.TelecomCorp.dbo.PropInfo from trigger on PropInfoXref table', 1, 1) ROLLBACK TRAN GOTO lblFail END
GOTO lblSuccess END GOTO lblSuccess END
lblFail: Print 'Failed to update...' lblSuccess: Print 'Update successful...'
set XACT_ABORT OFF
GO |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|