一个触发器的例子
Tab_A表:ID[PK,varchar(10)],rank[varchar(10)],other[varchar(50)]
主键(不是自动编号,例如:0000000196),等级,其它
Tab_B表:ID[PK,varchar(10)],rank[PK,varchar(10)],A_ID[PK,int,not null]
主键(自动编号),等级(对应Tab_A的rank),Tab_A的ID
需求:
1.向Tab_A中插入rank和other时自动算出ID;
2.向Tab_A中插入数据时当rank不为0时将Tab_A的ID和rank字段插入到Tab_B中;
在Tab_A上建立触发器如下:
触发器:
--------------------------------------------------------------------------------------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
create TRIGGER [trigger_a] ON [dbo].[Tab_A]
for INSERT
AS
begin
declare @m int ,@s varchar(30),@rank varchar(10)
select @m=max(cast(ID as integer)) from tab_A
set @m=@m+1
set @s=cast(@m as varchar)
while (len(@s)<10)
begin
set @s='0'+@s
end
update tab_A set ID=@s from inserted where tab_A.id=inserted.id
select @rank=rank from inserted
if(@rank!='0')
insert into tab_B(A_ID,rank) values(@s,@rank)
end;