sql触发器INSERT中如何过滤重复记录,望大虾赐教!
基表t306 党员表t55
id f3(姓名) f38(政治职务) id f1(姓名)
225 张 党员
266 刘 群众
248 王 党员
(实现功能将t306表中职务为党员的插入t55)
触发器
CREATE TRIGGER gz ON [dbo].[T306]
FOR INSERT
AS
insert t55(ID,f1) (select id ,f3 from t306 where F38=3)
新增一条新数据执行后返回
党员表t55
id f3(姓名) f38(政治职务)
225 张 党员
248 王 党员
299 赵 党员
再次新增返回为
党员表t55
id f3(姓名) f38(政治职务)
225 张 党员
248 王 党员
299 赵 党员
225 张 党员
248 王 党员
299 赵 党员
344 李 党员
出现重复,小弟为初学,真心请教大虾解决办法,
[解决办法]
CREATE TRIGGER gz ON [dbo].[T306]
FOR INSERT
AS
insert t55(ID,f1) select id ,f3 from inserted where F38= '党员 '
GO
[解决办法]
create table t306(id int,f3 varchar(10),f38 varchar(10))
create table t55(id int,f1 varchar(10))
GO
CREATE TRIGGER gz ON [dbo].[T306]
FOR INSERT
AS
insert t55(ID,f1)
select id ,f3 from inserted where F38= '党员 '
GO
insert into t306 select 225, '张 ', '党员 '
insert into t306 select 266, '刘 ', '群众 '
insert into t306 select 248, '王 ', '党员 '
GO
select * from t55
GO
/*
id f1
----------- ----------
225 张
248 王
*/
drop TRIGGER gz
drop table t306,t55
GO
[解决办法]
也可以这样写,不过随着数据量的增加,性能将不怎么样:
CREATE TRIGGER gz ON [dbo].[T306]
FOR INSERT
AS
insert t55(ID,f1)
select
id,f3
from
T306
where
F38= '党员 '
and
not exists(select 1 from t55 where ID=T306.ID and f1=T306.f1)
GO
[解决办法]
考虑以下做法:
CREATE TRIGGER gz ON [dbo].[T306]
FOR INSERT
AS
insert t55(ID,f1)
select
id,f3
from
T306
where
F38= '党员 '
and
id not in(select distinct id from t55)
GO
以前输入数据只能用重新INSERT才可以
insert into t55
select
id,f3
from
T306
where
F38= '党员 '
and
id not in(select distinct id from t55)
[解决办法]
not exists(select 1 from t55 where ID=T306.ID and f1=T306.f1)改成
not exists(select 1 from t55 where ID=T306.ID and f1=T306.f3)
lz似乎没理解语句里的意思
已经存在的重复数据可以用语句剔掉,参考一下语句
alter table dbo.tb1 add autoid int identity(1,1)--增加自动编号字段
go
delete dbo.tb1 --删除
where autoid not in(
select min(autoid) from dbo.tb1 group by clo...)--...是autoid外所有字段
go
alter table dbo.tb1 drop column autoid--删除自动编号字段
[解决办法]
CREATE TRIGGER gz ON [dbo].[T306]
FOR INSERT
AS
insert t55(ID,f1)
select
id,f3
from
T306
where
F38= '党员 '
and
not exists(select 1 from t55 where ID=T306.ID and f1=T306.f3) --此处修改为f3
GO
另外,如果存在数据遗失的情况,可以在查询分析器中写SQL把前期写入T306的数据追加到T55:
insert t55(ID,f1) select id ,f3 from inserted where F38= '党员 '