关于SQL触发器的简单应用 (转)
触发器
先建两个表
CREATE TABLE [dbo].[b] (
[BID] [int] IDENTITY (1, 1) NOT NULL ,
[AID] [int] NOT NULL ,
[BStr] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[a] (
[AID] [int] IDENTITY (1, 1) NOT NULL ,
[AStr] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[AStr2] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
--------下面分别是insert/delete/update触发器
CREATE TRIGGER [insertA] ON [dbo].[b]
FOR INSERT
AS
begin
insert into a(AStr,AStr2)
select top 1 BStr,BStr from inserted
end
CREATE TRIGGER [delAID] ON [dbo].[b]
FOR DELETE
AS
delete from a where a.AID in (select AID from deleted)
CREATE TRIGGER [upA] ON [dbo].[b]
FOR UPDATE
AS
if UPDATE(AID) or update(BStr)
begin
Update a
Set a.AStr=b.BStr
From b
Where a.AID=b.AID
end