I have a database of servers and some servers were entered with the fully qualified domain name. I want to rename all of these. However, in some instances the server has been entered both ways. For instance, servername.domain.com and servername. When I run my query below, these cause an error because of course that column can only contain unique records.

UPDATE ServerData
SET    ServerName = replace(ServerName, '.domain.com', '')
WHERE  ServerName LIKE '%.domain.com';

Error "Cannot insert duplicate key row in object 'dbo.ServerData' with unique index 'UK_ServerData'."

How can I modify the query to simply ignore records that would generate an error so I can deal with them individually later?


This will check to make sure the value you are writing doesn't already exist in that field:

SET    ServerName = replace(ServerName, '.domain.com', '')
FROM serverdata S
WHERE  ServerName LIKE '%.domain.com'
                FROM serverdata s2
                WHERE s2.servername = <> replace(s1.ServerName, '.domain.com', ''))
  • I didn't use your answer exactly, but the "FROM serverdata S" helped fix the query I had developed. Thanks! – Devil's Advocate Jan 17 '12 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.