Friday, April 26, 2013

SQL Server Interview Question and answers:- Triggers, Instead of triggers, after triggers, inserted and deleted tables?

Triggers are special kind of stored procedure which have logic's.These logics can be executed after or before data modification happens on a table.There are two types of triggers “Instead of triggers" and "After triggers".

Instead of triggers logic executes prior to data modification while after trigger logic executes after data modification.




In what scenarios will you use instead of trigger and after trigger?

You will use "INSTEAD trigger" to take alternative actions before the update happens.

Some of the uses of instead of trigger's are:-
•Reject updates which are not valid.
•Take some alternative action if any error occurs.
•To implement cascading deletes.For instance you want to delete a customer record.But in order to delete the customer record you also have to delete address records. So you can create a instead of trigger which will first delete the address table before executing delete on customer table.

While "AFTER trigger" is useful when you want to execute trigger logic after the data has been updated.

Some uses of after triggers are:-

•For recording Audit trail where you want new and old values to be inserted in to audit table.
•Updating values after the update has happened.For instance in a sales table if number of products and per product is inserted, you can create an after trigger which will calculate the total sales amount using these two values.

What are inserted and deleted tables?

During triggers we sometimes need old and new values.Insert and deleted tables are temporary tables created by SQL server itself which have new and old values.Inserted tables have one record for newly added data and deleted table has one record of the old version of the data.

So for instance let's say we add a new record called as "Shiv". The inserted table will have "Shiv" and deleted table will have nulls because the record did not exist.Now let’s say some user updates "Shiv" to "Raju".Then inserted table will have "Raju" and deleted tables will have "Shiv".

Also watch my most asked SQL Server interview question video on:- What is the difference between clustered and non-clustered indexes?

Taken from the best selling SQL Server interview question book,you can see more about the book by clicking on  SQL Server interview questions book.

1 comment:

Learning Networking Python said...

sir my name is venu am learning .net am fresher sir plz send the asp.net& C#.NET full note with exampls