Monday 20 March 2017

DML Operations on Views


Simple views:

     Views with simple select statements are updatable with normal DML statements. More precisely If the database system can determine the reverse mapping from the view schema to the schema of the underlying base tables, then the view is updatable. 

Example:

You can see actual underlying table is updated.

Read Only Views:

If DBMS cannot map the changes to the underlying base tables. 
The views with following clause in the select statements are readonly
  1. Group by
  2. Distinct
  3. aggregates 
  4. pivot
  5. unpivot
We can use instead of triggers to update these views.

Instead Of Trigger:

Instead Of Insert trigger can be used to perform the operations when there is an insert performaed on the view. Example, we can insert the data into the underlying table when there is an insert performed on the view. 

Example


CREATE TRIGGER [InsteadTrigger_Name] on TestView
INSTEAD OF INSERT
AS
BEGIN
  INSERT INTO [Raghu].[dbo].[Test]
       SELECT Color, Material
       FROM inserted
END;
GO

Please feel free to comment if you need any other information, Or you want to add more.