+ -
当前位置:首页 → 问答吧 → 关于触发器的问题请教

关于触发器的问题请教

时间:2011-12-16

来源:互联网

有这样两个表(Id均为自动增长字段):
T1:Id,Product_Name
T2:Id,Sales,Product_Name,Sale_Date

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

请高手帮忙。谢谢!

作者: sdctcl   发布时间: 2011-12-16

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


如果T1的ID是自增的话,把它从 select 列表中去掉就行了.

作者: qianjin036a   发布时间: 2011-12-16

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


作者: ssp2009   发布时间: 2011-12-16

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

作者: fredrickhu   发布时间: 2011-12-16

用程序的東西放在數據庫,不推薦

應該先維護T1表,T2表引用T1用的ID字段就行了

作者: roy_88   发布时间: 2011-12-16

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 行受影响)
*/

作者: pengxuan   发布时间: 2011-12-16

引用 4 楼 roy_88 的回复:
用程序的東西放在數據庫,不推薦

應該先維護T1表,T2表引用T1用的ID字段就行了


确实本来应该像您说的这样,主要是现在不方便改程序。

作者: sdctcl   发布时间: 2011-12-16