日期:2014-05-18 浏览次数:20538 次
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
------解决方案--------------------
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字段就行了
------解决方案--------------------
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 行受影响) */