Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

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

UPDATE s
SET    ServerName = replace(ServerName, '.domain.com', '')
FROM serverdata S
WHERE  ServerName LIKE '%.domain.com'
AND NOT EXISTS (SELECT 1 
                FROM serverdata s2
                WHERE s2.servername = <> replace(s1.ServerName, '.domain.com', ''))
share|improve this answer
    
I didn't use your answer exactly, but the "FROM serverdata S" helped fix the query I had developed. Thanks! –  Scott Beeson Jan 17 '12 at 16:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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