Search code examples
sql-serverjoinnullsql-viewisnull

SQL Server view based on JOIN two tables - how to replace NULL values with spaces?


I'm creating a view for some external system. This external system does not work with null values so I want to change them to some more user-friendly, by example "".

I use this query to create my view:

CREATE VIEW SomeView 
AS
   SELECT 
       r.CountryRegionCode, r.Name, e.ExampleData
   FROM 
       AdventureWorks2008.Person.CountryRegion r
   JOIN 
       AdventureWorks2008.dbo.SomeTable e ON r.CountryRegionCode = e.CountryRegionCode

The result of this query is:

enter image description here

As I understand I can use ISNULL operator to replace NULL with space, but how to use it in my statement? How to do it right:

SELECT 
    ISNULL (r.CountryRegionCode, 0) AS r.CountryRegionCode
     -- ..

?

Update: It does not understand what the r is:

enter image description here

Update #2: thank you guys very much! The final result:

SELECT 
    CountryRegionCode = ISNULL(r.CountryRegionCode, ''),
    Name = ISNULL(r.Name,''),
    ExampleData = ISNULL(e.ExampleData,'')
FROM 
    AdventureWorks2008.Person.CountryRegion r
JOIN 
    AdventureWorks2008.dbo.SomeTable e ON r.CountryRegionCode = e.CountryRegionCode

Solution

  • r is a table alias. If you want get column name r.CountryRegionCode need to quote them: [r.CountryRegionCode]

    CREATE VIEW SomeView
    AS
        SELECT CountryRegionCode = ISNULL(r.CountryRegionCode, ' '), -- COALESCE(r.CountryRegionCode, ' ')
               r.name,
               e.ExampleData
        FROM AdventureWorks2008.Person.CountryRegion r
        JOIN AdventureWorks2008.dbo.SomeTable e ON r.CountryRegionCode = e.CountryRegionCode
    

    Also please note about difference between COALESCE and ISNULL:

    DECLARE @a CHAR(1)
    SELECT ISNULL(@a, 'NULL') /*N*/, COALESCE(@a, 'NULL') /*NULL*/