Azuraith Azuraith - 2 months ago 7
SQL Question

Replace null values in a query that returns multiple values where only some of them are null?

Is there a way to replace every instance of null in a query?

I am using SQL Server 2008. For example if a query returns 4 values:

CustomerName:

Bob
Joe
Null
Alice


Can i replace the
Null
with
Allen
or any varchar/string?

Answer

Use COALESCE or ISNULL

SELECT CustomerName = COALESCE(CustomerName, 'Allen')
FROM dbo.TableName

If NULL isn't really NULL but the string 'NULL' you can use NULLIF + COALESCE / ISNULL:

SELECT CustomerName = COALESCE(NULLIF(CustomerName, 'NULL'), 'Allen')
FROM dbo.TableName