CREATE INSTEAD OF DELETE TRIGGER ON a view : Trigger on view « Trigger « SQL Server / T-SQL Tutorial






1>
2> SET NOCOUNT ON
3>
4> CREATE TABLE Table1
5> (a int  PRIMARY KEY,
6>  b datetime default getdate(),
7>  c varchar(10))
8>
9>
10> CREATE TABLE Table2
11>  (a int
12>   ,message varchar(100))
13> GO
1>
2> INSERT INTO Table1(a) VALUES (1)
3> INSERT INTO Table1(a) VALUES (2)
4> INSERT INTO Table1(a) VALUES (3)
5> INSERT INTO Table1(a) VALUES (4)
6>
7> INSERT INTO Table2 VALUES (1, 'first row')
8> INSERT INTO Table2 VALUES (1, 'second row')
9> INSERT INTO Table2 VALUES (2, 'first row')
10> INSERT INTO Table2 VALUES (2, 'second row')
11> INSERT INTO Table2 VALUES (2, 'third row')
12> INSERT INTO Table2 VALUES (3, 'first row')
13> GO
Msg 2627, Level 14, State 1, Server J\SQLEXPRESS, Line 2
Violation of PRIMARY KEY constraint 'PK__Table1__686944BF'. Cannot insert duplicate key in object 'dbo.Table1'.
The statement has been terminated.
Msg 2627, Level 14, State 1, Server J\SQLEXPRESS, Line 3
Violation of PRIMARY KEY constraint 'PK__Table1__686944BF'. Cannot insert duplicate key in object 'dbo.Table1'.
The statement has been terminated.
Msg 2627, Level 14, State 1, Server J\SQLEXPRESS, Line 4
Violation of PRIMARY KEY constraint 'PK__Table1__686944BF'. Cannot insert duplicate key in object 'dbo.Table1'.
The statement has been terminated.
Msg 2627, Level 14, State 1, Server J\SQLEXPRESS, Line 5
Violation of PRIMARY KEY constraint 'PK__Table1__686944BF'. Cannot insert duplicate key in object 'dbo.Table1'.
The statement has been terminated.
1>
2> CREATE VIEW join_view AS
3> SELECT Table1.a as a1, b, c,
4>        Table2.a as a2, message
5> FROM Table1 join Table2
6> ON Table1.a = Table2.a
7> GO
1>
2> CREATE TRIGGER DEL_JOIN
3> ON join_view
4> INSTEAD OF DELETE
5>
6> AS
7>   DELETE Table1
8>     WHERE a IN (SELECT a1 FROM deleted)
9>   DELETE Table2
10>     WHERE a IN (SELECT a2 FROM deleted)
11> GO
1>
2> drop TRIGGER DEL_JOIN;
3> drop VIEW join_view;
4>








22.9.Trigger on view
22.9.1.INSTEAD OF INSERT on a view
22.9.2.CREATE INSTEAD OF DELETE TRIGGER ON a view
22.9.3.INSTEAD OF UPDATE trigger on a view