触发器使用实例

//创建表Table_1
CREATE TABLE [dbo].[Table_1](
 [id] [int] NOT NULL,
 [result] [nchar](10) NOT NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
 [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

//创建表Table_2
CREATE TABLE [dbo].[Table_2](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [G_id] [int] NOT NULL,
 [C1] [nvarchar](50) NULL,
 [C2] [nvarchar](50) NULL,
 [C3] [nchar](10) NULL,
 CONSTRAINT [PK_Table_2] PRIMARY KEY CLUSTERED
(
 [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Table_2]  WITH CHECK ADD  CONSTRAINT [FK_Table_2_Table_2] FOREIGN KEY([id])
REFERENCES [dbo].[Table_2] ([id])
GO

ALTER TABLE [dbo].[Table_2] CHECK CONSTRAINT [FK_Table_2_Table_2]
GO

//插入测试数据

insert into [Table_1] (id,result) values (1,'未月结')
go

insert into Table_2 ([G_id],[C1],[C2],[C3]) VALUES (1,'aa','aa','aa')
insert into Table_2 ([G_id],[C1],[C2],[C3]) VALUES (1,'bb','bb','bb')
insert into Table_2 ([G_id],[C1],[C2],[C3]) VALUES (2,'cc','cc','cc')
go

//创建触发器

CREATE TRIGGER [dbo].[tri_table_1]
   ON  [dbo].[Table_1]
   AFTER UPDATE
AS
if Update(result)
BEGIN
update Table_2 set C2='ok'
from Table_2 t,  Deleted   d ,Inserted i
where i.id=t.G_id
 
 SET NOCOUNT ON;

    -- Insert statements for trigger here

END

GO

当执行 update Table_1 set result='已月结' where id=1  后 执行 触发器 tri_table_1 将 table_2 中 id为1 的 C2列 更新为 ok

你可能感兴趣的:(触发器)