-1

I am having two columns in table

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

but from now on I want to prevent following records

2   |   2
2   |   2
3   |   3
3   |   3

So I thought to create a unique index on these two columns but the table having so much existing data. So anything we can do this situation. Any suggestion?

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
Ankit Vaidya
  • 35
  • 1
  • 8

1 Answers1

0

you can use a trigger to prevent new rows being added with duplicate values

look at this example

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

A better solution would be to move the duplicates to a seperate table for history, and then add a check constraint on these 2 columns

EDIT

you could do it by an check constraint like this

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

where 12345 is the highest value of the column id now.
You will have to test it a bit if it works on all situations.
Also, it will only work if all new rows have a value in id that is larger then the current highest value (12345 in my example)

GuidoG
  • 11,359
  • 6
  • 44
  • 79