如何编写将表的列的值复制到另一个表的另一列的触发器?

时间:2013-04-05 08:05:06

标签: sql sql-server-2008 triggers

我有一张表 tblBilling tblTotalFee 。我在 tblBilling 中的一个列被命名为 RemainingAmount ,而在 tblTotalFee 中,我有另一个名为从上个月到期的列 。现在我想要的是,当我在剩余金额中插入一个值时,我希望该值自动插入从上个月到期。我正试图写一个触发器。但我不能正确吗?任何人都可以帮助我吗?

我试过了:

ALTER trigger [dbo].[trg_Billing_TotalFee] on [dbo].[tblBilling] 
after insert as 
insert into tblTotalFee(DueFromPreviousMonth) 
select RemainingAmount from inserted

1 个答案:

答案 0 :(得分:1)

举个例子:


create table tblBilling (ID int identity(1000,1) primary key,
                         RemainingAmount int 
                         )
go
create table tblTotalFee (ID int identity(1000, 1) primary key,
                          DueFromPreviousMongh int)
go 
create trigger tr_tblBillingSync on tblBilling 
after insert 
as 
    insert into tblTotalFee (DueFromPreviousMongh)
    select RemainingAmount from inserted
go 
insert into tblBilling 
select 25
union all select 27
union all select 33
go
select * from tblBilling
select * from tblTotalFee
go 

最终输出结果:


ID     |  RemainingAmount
-------------------------
1000   |    25
1001   |    27
1002   |    33

ID     |  DueFromPreviousMongh
-------------------------
1000   |    25
1001   |    27
1002   |    33