insert into t2 select f1 from inserted也不对啊,当在t1中insert两条记录时在t2中insert了4条, 当在t1中insert 3条记录时在t2中insert了9条, 当在t1中insert 4条记录时在t中insert了16条怎样解决啊?
--建表 create table tt1 (f1 int not null primary key) GO create table tt2 (f1 int not null primary key) GO --建触发器 create trigger trig1_insert on tt1 for insert as begin insert into tt2 select f1 from inserted end GO--测试 Select * from tt1 Select * from tt2 insert into tt1 select 1 union all select 2 union all select 3 Select * from tt1 Select * from tt2 --删除表 Drop table tt1 Drop table tt2 --结果 f1 1 2 3f1 1 2 3
create table t1 (f1 int not null primary key) Go create table t2 (f1 int not null primary key) Go create trigger trig1_insert on t1 for insert as begin declare @m int select @m=f1 from inserted --问题就出在这里,当记录不为一条时,SELECT 付值就把最后一条记录付给@M insert into t2 select @m Print @m end Go insert into t1 select 1 union all select 2 union all select 3 Go Select * From t1 Go Select * From t2 GoDrop Table t1 Go Drop Table t2 Go/*3 f1 ----------- 1 2 3(所影响的行数为 3 行)f1 ----------- 3(所影响的行数为 1 行)说明触发器执行了一次*/ --所以改写这句话为 insert into t2 select * From inserted 就可以了
当在t1中insert 3条记录时在t2中insert了9条,
当在t1中insert 4条记录时在t中insert了16条怎样解决啊?
--建表
create table tt1
(f1 int not null primary key)
GO
create table tt2
(f1 int not null primary key)
GO
--建触发器
create trigger trig1_insert on tt1
for insert
as
begin
insert into tt2 select f1 from inserted
end
GO--测试
Select * from tt1
Select * from tt2
insert into tt1 select 1
union all select 2
union all select 3
Select * from tt1
Select * from tt2
--删除表
Drop table tt1
Drop table tt2
--结果
f1
1
2
3f1
1
2
3
(f1 int not null primary key)
Go
create table t2
(f1 int not null primary key)
Go
create trigger trig1_insert on t1
for insert
as
begin
declare @m int
select @m=f1 from inserted
--问题就出在这里,当记录不为一条时,SELECT 付值就把最后一条记录付给@M
insert into t2 select @m
Print @m
end
Go
insert into t1 select 1
union all select 2
union all select 3
Go
Select * From t1
Go
Select * From t2
GoDrop Table t1
Go
Drop Table t2
Go/*3
f1
-----------
1
2
3(所影响的行数为 3 行)f1
-----------
3(所影响的行数为 1 行)说明触发器执行了一次*/
--所以改写这句话为 insert into t2 select * From inserted 就可以了