关于触发器的问题请教
有这样两个表(Id均为自动增长字段):
T1:Id,Product_Name
T2:Id,Sales,Product_Name,Sale_Date
能不能设计这样的触发器:在T2新增记录时,检查T1的Product_Name字段,如果T1中不存在T2新增记录中的Product_Name,则在T1中增加这个Product_Name?
请高手帮忙。谢谢!
[解决办法]
create trigger insertt1on t2for insertasbegininsert into t1select 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 t2for insertasbegininsert 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 T1gocreate table T1( Id int identity(1,1), Product_Name varchar(10))goif object_id('T2') is not null drop table T2gocreate 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_T2gocreate trigger tr_T2 on T2for insertas insert into T1 (Product_Name) select Product_Name from inserted a where not exists(select 1 from T1 where Product_Name=a.Product_Name) goinsert 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 T1select * from T2/*执行了三次插入,只有两次在T1中插入Id Product_Name----------- ------------1 毛巾2 香皂(2 行受影响)Id Sales Product_Name Sale_Date----------- ----------- ------------ -----------------------1 10 毛巾 2011-11-11 00:00:00.0002 20 香皂 2011-11-12 00:00:00.0003 10 毛巾 2011-11-13 00:00:00.000(3 行受影响)*/