9

here in this query I want to replace the values in Person.Contact of Adventureworks database with some new values. The below query case statement is working fine for other values but I am not able to change the values those are in NULL. I am using SQL Server. Any help is appreciated.

select contactid,Title,FirstName,MiddleName,
case MiddleName
when 'R.' then 'Robert'
when 'B.' then 'Bids'
when 'J.' then 'John'
when is null then 'New Name'
else 'No Name'
end, LastName from Person.Contact

3 Answers 3

16
case 
when MiddleName is null then ...
when MiddleName = 'R' then ...
end
Sign up to request clarification or add additional context in comments.

Comments

13

I'd use the ISNULL function - it will return the value given if the field is NULL:

select contactid,Title,FirstName,MiddleName,
case ISNULL(MiddleName, 'NULLVALUE')
when 'R.' then 'Robert'
when 'B.' then 'Bids'
when 'J.' then 'John'
when 'NULLVALUE' then 'New Name'
else 'No Name'
end, LastName from Person.Contact

4 Comments

I agree. Let's just hope that nobody has 'NULLVALUE' as middle name.
Is that like little Bobby DROP TABLES?
@JohnDunagan Well, our is less dangerous
For anyone interested in the story of bobby tables: Here you are.
5

Sorry to post 7 years later, but I've been trying to find a solution for Interbase / Firebird and this post kept popping up. None of the solutions here work because there is no ISNULL, so I figured I'd help anyone else who might come here looking for that:

select contactid,Title,FirstName,MiddleName,
case COALESCE(MiddleName, 'NULLVALUE')
when 'R.' then 'Robert'
when 'B.' then 'Bids'
when 'J.' then 'John'
when 'NULLVALUE' then 'New Name'
else 'No Name'
end, LastName from Person.Contact

3 Comments

Firebird does not have is null too (as opposed to isnull)?
Thank you very much.. Had the same trouble with using Interbase that doesn't have ISNULL but your code worked!
@GSerg Firebird might, but I was working in InterBase... Firebird seems to have more features, but anything that works in InterBase should work in Firebird, but not the other way around. Also, I saw all kinds of links to setup your own UDF for ISNULL, but that seemed a bit beyond what I was needing to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.