|
发器语句中使用了两种特殊的表:deleted 表和 inserted 表
Deleted 表用于存储 DELETE 和 UPDATE 语句所影响的行的复本。在执行 DELETE 或 UPDATE 语句时,行从触发器表中删除,并传输到 deleted 表中。Deleted 表和触发器表通常没有相同的行。
Inserted 表用于存储 INSERT 和 UPDATE 语句所影响的行的副本。在一个插入或更新事务处理中,新建行被同时添加到 inserted 表和触发器表中。Inserted 表中的行是触发器表中新行的副本。
select @id = id from inserted
select @id = id from deleted
--创建两张表
CREATE TABLE [dbo].[bb](
[a] [char](10) COLLATE Chinese_PRC_CI_AS NOT NULL,
[c] [nchar](10) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_bb] PRIMARY KEY CLUSTERED
(
[a] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Student](
[Sno] [char](5) COLLATE Chinese_PRC_CI_AS NOT NULL,
[Sname] [char](20) COLLATE Chinese_PRC_CI_AS NULL,
[Ssex] [char](1) COLLATE Chinese_PRC_CI_AS NULL,
[Sage] [int] NULL,
[Sdept] [char](15) COLLATE Chinese_PRC_CI_AS NULL,
[spic] [image] NULL,
CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
(
[Sno] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY],
UNIQUE NONCLUSTERED
(
[Sname] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY],
UNIQUE NONCLUSTERED
(
[Sno] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
--创建触发器
1. 创建插入触发器
create TRIGGER [trstudent4]
ON [dbo].[Student]
after INSERT
AS
declare @sno char(10)
begin
select @sno = sno from inserted
insert into bb(a) values(@sno)
end
2.创建删除触发器
create TRIGGER [trstudent5]
ON [dbo].[Student]
after delete
AS
declare @sno char(10)
begin
select @sno = sno from deleted
insert into bb(a) values(@sno)
end
3.创建更新触发器
create TRIGGER [trstudent6]
ON [dbo].[Student]
after update
AS
declare @sno char(10)
begin
select @sno = sno from inserted
if @sno != null
begin
insert into bb(a) values(@sno)
end
end
4.创建更新触发器
create TRIGGER [trstudent7]
ON [dbo].[Student]
after update
AS
declare @sno char(10)
begin
select @sno = sno from deleted
if @sno != null
begin
insert into bb(a) values(@sno)
end
end
其中3与4的功能是一样的. |
|