日期:2014-05-18 浏览次数:20701 次
CREATE TABLE [dbo].[table1](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](50) NULL,
    [bank] [varchar](50) NULL,
    [account] [int] NULL,
    [salary] [float] NULL
) ON [PRIMARY]
GO
insert table1([name],[bank],[account],[salary])
select 'AAA','IC',1111,200 union all
select 'BBB','AB',2222,300
---------------------------------------------
create trigger newRecInsert
on table1
after insert
as
if exists (select top 1 * from table1,inserted where table1.name=inserted.name)
begin
    declare @bank varchar(50),@account int
    select @bank=table1.bank,@account=table1.account from table1,inserted 
    where table1.name=inserted.name and table1.bank is not null
    update table1 set bank=@bank,account=@account
    from table1,inserted
    where table1.name=inserted.name
end
---------------------------------------------
insert table1([name],[salary])
select 'AAA',400
select * from table1
drop table table1
------解决方案--------------------
create table taba
(id int identity(1,1), 
 name varchar(5),
 bank varchar(5),
 account varchar(5),
 salary int
)
insert into taba(name,bank,account,salary)
select 'AAA', 'IC', '1111', 200 union all
select 'BBB', 'AB', '2222', 300
create trigger tr_taba
on taba instead of insert
as
begin
 insert into taba(name,bank,account,salary)
 select i.name,
        isnull(bank,(select top 1 bank from taba where name=i.name)),
        isnull(account,(select top 1 account from taba where name=i.name)),
        salary
 from inserted i
end
insert into taba(name,salary) select 'AAA',400
select * from taba
/*
id          name  bank  account salary
----------- ----- ----- ------- -----------
1           AAA   IC    1111    200
2           BBB   AB    2222    300
3           AAA   IC    1111    400
(3 row(s) affected)
*/