对sql场景的建议

对sql场景的建议,sql,sql-server,database,business-logic,unique-index,Sql,Sql Server,Database,Business Logic,Unique Index,表中有两列 InventoryId | RevisionId ------------------------- 1 | 1 2 | 1 2 | 2 2 | 2 3 | 1 3 | 2 3 | 3 3 | 3 但从现在起,我想阻止以下记录 2 | 2 2 | 2 3 | 3 3 | 3 所以我想在这两列上创建一个唯一的索引 但是这个表有这么多现有数据。在这种情况下,我们可以做任何事情。 有什么建议

表中有两列

InventoryId | RevisionId
-------------------------
1   |   1
2   |   1
2   |   2
2   |   2
3   |   1
3   |   2
3   |   3
3   |   3
但从现在起,我想阻止以下记录

2   |   2
2   |   2
3   |   3
3   |   3
所以我想在这两列上创建一个唯一的索引 但是这个表有这么多现有数据。在这种情况下,我们可以做任何事情。
有什么建议吗?

您可以使用触发器防止添加具有重复值的新行

看看这个例子

create trigger TR_UI_YourTable on YourTable
for update, insert as
begin
     set nocount on

     if exists (select 1 from inserted i where i.InventoryId = i.RevisionId)
     begin
          ;throw 99001, 'no dupes allowed anymore...', 1
     end
end
更好的解决方案是将副本移动到单独的历史记录表中,然后在这两列上添加检查约束

编辑

您可以通过像这样的检查约束来完成

alter table yourtable
add constraint chk_dupes 
  check ((InventoryId <> RevisionId) or (id <= 12345))
altertableyourtable
添加约束chk_重复

检查((库存ID修订ID)或(id,因此允许使用现有数据
2 | 2
,但任何新行可能都不具有相同的值?每行上是否有唯一的id?您应该删除重复的值并添加唯一的键您可以先删除现有的重复值,然后添加唯一的键,或者现在使用trigger@Mano桌子上有这么多的食物f可作为历史使用的现有数据,因此我不能这样做