关于SQL SERVER触发器,能触决我的问题,立刻给分
table1
id,productname,account
table2
id,table1_id,tm_code
在table1上写增加的触发器,想实现:
当table1插入一条记录后,在table2插入account条记录.
看例子:
table1
id,productname,account
2 手板 3
table2
id,table1_id,tm_code
1 2 45433-1
2 2 45433-2
3 2 45433-3
现在我更关心的是,如何在table2插入这3条记录.请帮忙.
以下触发器代码是出错的:
……
for i=1 to @account
begin
insert into table2(table1_id,tm_code) values(@table1_id,@tm_code)
end
next
……
------解决方案--------------------草写如下
create trigger tri_name on table1
as
declare @account int
declare @i int
set @i=0
select @account=account from inserted
while @i <@account
begin
insert into table2(table1_id,tm_code) values(@table1_id,@tm_code)
set @i=@i+1
end
go
------解决方案--------------------create table table1(id int,productname varchar(10),account int)
create table table2(id int identity(1,1),table1_id int,tm_code varchar(20))
go
create trigger trg_a on table1
for insert
as
begin
declare @i int,@account int,@table1_id int
select @account=account,@table1_id=id,@i=0 from inserted
while @i <@account
begin
set @i=@i+1
insert into table2(table1_id,tm_code) values(@table1_id, '45433- '+rtrim(@i))
end
end
go
insert into table1 select 2, '手板 ',3
select * from table2
/*
id table1_id tm_code
----------- ----------- --------------------
1 2 45433-1
2 2 45433-2
3 2 45433-3
*/
go
drop trigger trg_a
drop table table1,table2
go