关于触发器解决方法

关于触发器
根据百度知道,自己练习了下触发器,发现无法达到需要的要求,来问下大大们

原地址:
http://http://zhidao.baidu.com/link?url=K07ORA1KBpKY647I5bP8l7XAzQJ9Phr8_68huRLZAtbZ_rvg19ZiVqk6xI67mG8LXBP4VrtYQgipyQr-N2Ae8a
create table tbA
(myid int primary key,  
myx decimal(10,2),
myy int)

create table tbB
(myid int foreign key references tba(myid),
mysum decimal(10,2))


if (OBJECT_ID('tr_mo','tr')is not null)
 drop trigger tr_mo
go 
create trigger tr_mo
on tba
for insert,update
as
declare @id int,
        @x decimal(10,2),
        @y int
begin
select @id=myid,@x=myx,@y=myy from inserted
update tbB set mysum=(@x*@y+mysum) where tbb.myid=@id
end

我对tbA表进行
insert into tba values(1,1000,1)
insert into tba values(2,2000,1)

但是tbB表完全没有东西
执行的时候显示
(0行受影响)
(1行受影响)
------解决思路----------------------
引用:
Quote: 引用:



你的这个语句:

begin
select @id=myid,@x=myx,@y=myy from inserted
update tbB set mysum=(@x*@y+mysum) where tbb.myid=@id
end

会导致tbb里肯定是没有影响的,因为你是按照@id的值查找是否有满足的记录,然后进行更新,结果由于tbb这个表本来就是空的,当然就会找不到任何的记录。

于是 insert 表tba的记录肯定是插进去了,但是tbb还是空的

那如果我要完成这个业务需求该怎么改呢


你先往 tbb表里插入1条记录,这条记录的myid 的值,是接下来要插入到tba表中的myid值