Link to home
Start Free TrialLog in
Avatar of Lorik
Lorik

asked on

how to update one record when there are duplicates?

Is there a way to update only one record when there are duplicate records in the table?  
The reason there are duplicates is because the distinct key fields haven't been populated yet, but I need to perform an update on only one particular record before I can fill in the distinct key fields.  Any suggestions?
Avatar of mcix
mcix

An easy way would be to have an identity field in your table.  On the insert, you could return the @@Identity variable to your code from a stored proc that does the insert.  With that value, you would have a unique criteria for the where clause for the update.

If you can't modify the table struct, there are possibly other ways.
I know this would work in Sybase SQL Server, not sure in MS SQL, but give it a try (on a test table, please!).
-- limit action to a single row
set rowcount 1
go
update mytable
where dupkeyvalue = <x>
go
-- return to affecting full set of rows
set rowcount 0
go

Avatar of Lorik

ASKER

MS-SQL doesn't have ROWCOUNT funtion, I wish it did.
ASKER CERTIFIED SOLUTION
Avatar of DennisH
DennisH

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Lorik,

I'm not sure I understand exactly what you're trying to do.  If I understand your question, you might want to do an UPDATE...WHERE, something like:

UPDATE table SET <whatever>
WHERE <afield> = (select distinct <afield> from table)

This may give you a starting point, again depending on what exactly you want to do.

Don
Lorik,

Sorry, I wasn't thinking straight.  What I wrote before will not work.  Please ignore it.

If you want to update only one row, you have to find something unique about it.  It doesn't have to be a key, but it has to be unique.  

Otherwise you have to do something procedural like using a cursor to find the set, fetch the first record and then update it.  Let us know if you need help with this.  :)

Don