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

关于触发器的问题请教
有这样两个表(Id均为自动增长字段):
T1:Id,Product_Name
T2:Id,Sales,Product_Name,Sale_Date

能不能设计这样的触发器:在T2新增记录时,检查T1的Product_Name字段,如果T1中不存在T2新增记录中的Product_Name,则在T1中增加这个Product_Name?

请高手帮忙。谢谢!

------解决方案--------------------
SQL code
create trigger insertt1
on t2
for insert
as
begin
insert into t1
select id,product_name from inserted a where not exists(select 1 from t1 where product_name=a.product_name)
end

------解决方案--------------------
create trigger insertt1
on t2
for insert
as
begin
insert into t1
select id,product_name from inserted a 
where not exists(select 1 from t1 where product_name=a.product_name)
end



------解决方案--------------------
SQL code
create tigger test on t2
for insert
as
begin
insert into
 t1(Product_Name) 
select
 Product_Name 
from
 inserted i 
where
 not exists(select 1 from t1 where Product_Name=i.Product_Name)
end

------解决方案--------------------
用程序的東西放在數據庫,不推薦

應該先維護T1表,T2表引用T1用的ID字段就行了
------解决方案--------------------
SQL code

if object_id('T1') is not null
   drop table T1
go
create table T1
(
 Id int identity(1,1),
 Product_Name varchar(10)
)
go
if object_id('T2') is not null
   drop table T2
go
create table T2
(
 Id int identity(1,1),
 Sales int,
 Product_Name varchar(10),
 Sale_Date datetime
)
go
--创建触发器
if object_id('tr_T2') is not null
   drop trigger tr_T2
go
create trigger tr_T2 on T2
for insert
as
  insert into T1 (Product_Name) select Product_Name from inserted a where not exists(select 1 from T1 where Product_Name=a.Product_Name) 
go

insert into T2(Sales,Product_Name,Sale_Date) select 10,'毛巾','2011-11-11'
insert into T2(Sales,Product_Name,Sale_Date) select 20,'香皂','2011-11-12'
insert into T2(Sales,Product_Name,Sale_Date) select 10,'毛巾','2011-11-13'

select * from T1
select * from T2
/*
执行了三次插入,只有两次在T1中插入
Id          Product_Name
----------- ------------
1           毛巾
2           香皂

(2 行受影响)

Id          Sales       Product_Name Sale_Date
----------- ----------- ------------ -----------------------
1           10          毛巾           2011-11-11 00:00:00.000
2           20          香皂           2011-11-12 00:00:00.000
3           10          毛巾           2011-11-13 00:00:00.000

(3 行受影响)
*/