I have some database corruption and need to write an SQL script to rectify it.
Basically I have something similar to the following
and some typical data might look like
so each entry for a model should have a unique ClientID. But you will note that model 1 has duplicate rows for clientID -2 & -3
Now I cant delete these duplicate rows, instead I need to update the ClientID value. So for ID 3 I need to update the ClientID to -4 and for ID 5 I need to update the ClientID to -5. (basically the next available ID)
Hopefully you're still following me
I have written a query to get the duplicate rows from the table and tell me what the current highest ClientID used for that Model is.
So this query will give me something like
How can I tweak the above query so I do an update and change the ClientID to "HighestClientID" + 1. In the above result set it would work for the first row, but not the second. i.e. it would still leave me with duplicates for ClientID -3
Basically I have something similar to the following
Code:
table1
{
ID int PK
ModelID int FK
ClientID int
}
and some typical data might look like
Code:
ID ModelID ClientID
1 1 -1
2 1 -2
3 1 -2
4 1 -3
5 1 -3
6 2 -1
7 2 -2
8 2 -3
so each entry for a model should have a unique ClientID. But you will note that model 1 has duplicate rows for clientID -2 & -3
Now I cant delete these duplicate rows, instead I need to update the ClientID value. So for ID 3 I need to update the ClientID to -4 and for ID 5 I need to update the ClientID to -5. (basically the next available ID)
Hopefully you're still following me

Code:
select
t1.ClientID,
t1.ModelID,
(SELECT TOP(1) KnowdeID from Table1 where ModelID = t1.ModelID and ClientID = t1.ClientID) ID,
(SELECT min(ClientID) from Table1 where ModelID = t1.ModelID) HighestClientID
from Table1 t1
group by t1.ClientID, t1.ModelID
having count(t1.ClientID) > 1
So this query will give me something like
Code:
ClientID ModelID ID HighestClientID
-2 1 3 -3
-3 1 5 -3
How can I tweak the above query so I do an update and change the ClientID to "HighestClientID" + 1. In the above result set it would work for the first row, but not the second. i.e. it would still leave me with duplicates for ClientID -3