Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Update a key column

Status
Not open for further replies.

urya

MIS
Jun 5, 2003
5
US
When I run "update MYTABLE123 SET ColumnA=ColumnB"
I get the following message.

Msg 2627, Level 14, State 1, Server MYSERVER\MYSQL, Line 1
Violation of PRIMARY KEY constraint 'MYTABLE123'. Cannot insert duplicate key in
object 'MYTABLE123'.
The statement has been terminated.

The constraint says "CREATE UNIQUE" & "Constraint".
I cannot modify that value. (and I don't think I should)

I can manually update the column by hand but I just cannot update all at once.
I have thousands of records which I cannot do it manually...

Plase help.

Thanks.

Urya
 
So, you have a unique constraint on ColA but there are duplicate values in ColB. You need to fix these in order to insert them into ColA.

To find the duplicates:

Code:
SELECT ColB, COUNT(*)
FROM t
GROUP BY ColB
HAVING COUNT(*) > 1

--James
 
James,

Thanks.
I'll try to eliminate duplicates...
I pretty much know where they are...
I guess my only way is to copy the duplicate column(colB) to a new table (colB'), replace the colB with something else, and copy colB' back to colA.

So to copy back ColB' to ColA,
I should:
UPDATE TableA
SET ColA = TableB.ColB
WHERE TableA.ID = TableB.ID

Would this work?

Urya

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top