日期:2014-05-18  浏览次数:20515 次

关于利用触发器POST数据的问题.谢谢!
1.数据表(A表):
Number     Chinesename     Old     New     Date                 POST
A00001         张三               100     200     2007-05-01       N

2.触发器(如果A表的POST项为 "Y "时,把这条数据插入到B表):
CREATE   trigger   tg_test
on   dbo.A表  
for   update  
as  
declare   @Number   int
declare   @Post   varchar  
declare   @New   int

select   @New=Newy,@Post=Post,@Number=Number   from   inserted  
if     @Post= 'Y '
begin

insert   into   B表(Number,ChineseName,Old,New,TakeEffectDate)

Select   Number,ChineseName,Old,New,TakeEffectDate   from   A表

end
3.问题:
当A表里面的数据的POST项为 "Y "时,只要我修改这条记录都会再次插入这条数据到B表.因为这条记录其实已经POST过B表了,但当我一修改时又再POST一条过去.怎样修改一下呢?谢谢!



------解决方案--------------------
--这个触发器应该这么写
--原触发器好多隐患

CREATE trigger tg_test
on dbo.A表
for update
as

insert into B表(Number,ChineseName,Old,New,TakeEffectDate)
Select i.Number,i.ChineseName,i.Old,i.New,i.TakeEffectDate
from insert i,deleted d
where i.Number=d.Number --这里假设Number是主键而且不允许修改
and i.Post= 'Y '
and d.Post= 'N '


end

------解决方案--------------------
CREATE trigger tg_test
on dbo.A表
for update
as
declare @Number int
declare @Post varchar
declare @New int
declare @Old int
declare @ChineseName nvarchar
declare @TakeEffectDate datetime
select @New=Newy,@Post=Post,@Number=Number,@Old=Old,@ChineseName=ChineseName,@TakeEffectDate=TakeEffectDate from inserted
if @Post= 'Y '
begin
if not exists (select Number from B表 where Number=@Number )
insert into B表(Number,ChineseName,Old,New,TakeEffectDate) values(@Number,@ChineseName,@Old,@New,@TakeEffectDate)
end
--实现A表的记录更改后B表的同一条记录也同时更改
if not exists (select Number from B表 where Number=@Number )
Begin
update B表 set ChineseName=@ChineseName , Old=@Old , New=@New , TakeEffectDate=@TakeEffectDate
where Number=@Number

end


实现A表的记录更改后B表的同一条记录也同时更改
你说的同一条记录应该又一个字段关联 ,这里用的是
Number