Monday, August 15, 2005

Relation between Triggers and sp_dbcmptlevel

SQL Server 2000 allows multiple triggers to be created for each data modification event (Delete, Insert or Update). If we create a Insert trigger to a table which already has an insert trigger then both Insert triggers would be created.

The same doesn't hold good for SQL Server 6.5. In version 6.5 a table can have only one trigger for each data modification event. i.e., if we try to create an Insert trigger for a table which already has an Insert trigger then the latest trigger would replace the earlier created trigger.

Lets test and check that for ourself. Use the below code snippet to create a sample table for the purpose of understanding this artcile.

Table Structure:

Create Table testTrigger
(
Sno int Identity (1,1),
FirstName Varchar(25),
Age int
)

Create Insert triggers for this table:

Create Trigger trgTriggerOne on testTrigger
for Insert
As
Print 'Trigger trgTriggerOne is fired ...'
Go

Create Trigger trgTriggerTwo on testTrigger
for Insert
as
Print 'Trigger trgTriggerTwo is fired'
Go

Now let us insert a sample record and see what happens.

Insert into testTrigger values ('vadivel',29)

Both 'Trigger trgTriggerOne is fired ...' and 'Trigger trgTriggerTwo is fired' would be displayed. Before testing the same stuff in SQL Server 6.5 let us drop both the trigger here.

Drop trigger trgTriggerOne
Drop trigger trgTriggerTwo

Run the below code snippet to change the compatibility level to SQL Server 6.5

sp_dbcmptlevel testdb, 65

Now try and create two Insert trigger for the same table and see what happens.

Create Trigger trgTriggerOne65 on testTrigger
for Insert
As
Print 'Trigger trgTriggerOne65 is fired ...'
Go

Create Trigger trgTriggerTwo65 on testTrigger
for Insert
as
Print 'Trigger trgTriggerTwo65 is fired'
Go

No errors trigger has been created. Now let us try and insert a sample record to see what happens.

Insert into testTrigger values ('Vadivel', 29)

Only the message 'Trigger trgTriggerTwo65 is fired' would be displayed. Its because that trigger has overwritten the trigger trgTriggerOne65 while creation itself.

Clean Up:

Drop trigger trgTriggerTwo65
Drop table testTrigger

Change the compatibility level again to SQL Server 2000:

sp_dbcmptlevel testdb, 80

No comments: