SQL场景建议

时间:2019-03-27 11:42:57

标签: sql sql-server database business-logic unique-index

我表中有两列

Object

但是从现在开始,我要防止跟踪记录

InventoryId | RevisionId
-------------------------
1   |   1
2   |   1
2   |   2
2   |   2
3   |   1
3   |   2
3   |   3
3   |   3

所以我想在这两列上创建一个唯一索引 但是表格中有太多现有数据。所以我们可以做这种情况。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

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

看这个例子

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

更好的解决方案是将重复项移到单独的表中进行历史记录,然后在这2列上添加检查约束

编辑

您可以通过这样的检查约束来做到

alter table yourtable
add constraint chk_dupes 
  check ((InventoryId <> RevisionId) or (id <= 12345))

其中12345是列id的最高值。
如果在所有情况下都可以运行,则必须对其进行一点测试。
另外,只有在所有新行中的id中的值都大于当前的最大值(在我的示例中为12345)时,它才起作用。