我在SQL Server 2008 R2中的重复条目中遇到困难。由于该计划的性质,我被告知独特的约束不是一种选择。SQL Server中具有相同插入语句的重复条目
有人可以请帮助,因为我已经尝试了插入触发器,但没有运气。
表结构:
col1 - identity
col2 - filename
col3 - date
col4 - filetype
col5 - process
col6 - userid
col7 - info
当运行此insert
第一次时,它进入两者中的条目。我不想要的:
insert into table(filename, filetype,process, userid)
values
('test9','import','view','tester'),
('test9','import','view','tester')
该条目现在在表中是两次,唯一的区别是标识列。
Identity Filename Date Filetype Process Userid Info
17 Test9 2014-01-31 Import View test null
18 Test9 2014-01-31 Import View test null
当我运行完全相同的插入第二次,然后不插入,因为它然后将其视为重复。为什么第一次没有看到它是重复的?
这里是我创建的触发器:
Create trigger check_duplicates
on table
for insert
as
if not exist (select p.filename, p.date
from table p, inserted i
where p.filename = i.filename and p.date = i.date)
insert into table
select filename, date, filetype, process, userid, info
from inserted
else
raiserror('Duplicate file exist',16,1)
rollback
end
谢谢
'inserted'是表不是一个单一的记录,你有插入表加入。 –
您需要将'else'中的'raiserror'和'rollback'放入'BEGIN .... END'代码块中,否则每次触发器运行时都会执行'ROLLBACK'! –