Example of a view trigger.

Source: Internet
Author: User

/* Create Table usertable
(
Userid uniqueidentifier not null rowguidcol, -- Unique Identifier
Name nvarchar (60) null, -- name

Age int null default 0 check (age> 20), -- Age

Address nvarchar (25) null -- Address
)*/
Go

Create Table logtable1
(
Name nvarchar (60) null,
Age int
)
Go
Create Table logtable2
(
Name nvarchar (60) null,
Age int
)

Go
Insert logtable1 values ('t11', 30)

Insert logtable1 values ('t12', 40)

Insert logtable1 values ('t13', 50)

Insert logtable2 values ('t21', 130)

Insert logtable2 values ('t22', 140)

Insert logtable2 values ('t23, 150)
Insert logtable2 values ('t24', 160)

Select * into logall from logtable1 Union select * From logtable2

Go
-- Create View
Create view logview
As
Select * From logtable1 Union select * From logtable2

-- Create trigger of delete in view
Create trigger logview_delete on logview instead of Delete
As
Begin
Delete logall where name in (Select name from deleted)
End
Go

-- Create trigger of insert in view
Create trigger logview_insert on logview instead of insert
As
Begin
Insert logall select * From inserted
End
Go

-- Create trigger of update in view
Create trigger logview_update on logview instead of update
As
Begin
Set nocount off
If not exists (select * From inserted) Return
 
Declare @ name varchar (20)
Declare @ oldname varchar (20)
Declare @ age int

Select @ name = Name, @ age = age from inserted
Select @ oldname = Name from deleted

Update logtable1 set name = @ name, age = @ age where name = @ oldname
Update logtable2 set name = @ name, age = @ age where name = @ oldname
/*
 
If @ namer is null and @ age is null
Begin
Raiserror (1074008065, 16,127) with Nowait, seterror
Return
End

If (Update (name ))-
Begin
Exec p_getname
End
*/

End

-- Test
Delete logview where name = 't11'

Insert logview values ('v1 ', 100)

Update logview set name = 't121212', age = 10000 where name = 't12'

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.