Fetch all data when 'where statement" can contain null SQL-server 2012

I am trying to get some data on my web page in a table using SQL server 2012 but i'm having a hard time writing my SELECT query. This is what I have so far:

SELECT DISTINCT a.Id_972 Id, 
                a.Datum_972 Date, 
                a.Omschrijving_972 Title, 
                a.Bedrag_972 Amount, 
                b.OmschrN_977 Type, 
                c.OmschrKN_976 Project, 
                d.Status_975 Status    
FROM WebOnkosten_972 AS a, 
     WebOnkostenType_977 AS b, 
     WebOnkostenProject_976 AS c, 
     WebOnkostenToestand_975 AS d    
WHERE a.Type_972 = b.Type_977' AND 
      a.Project_972 = c.ProjectNR_976 AND 
      a.Id_972 = d.IdOnkost_975

This straight forward Select query get the data like it should, but it is not exactly what I want.

Im fetching my project name from table 'c' with an id in table 'a'.

My problem here is that it is possible that projects can be nulls. But I still want to get every record. I want to show this data in a table. I want to have an emtpy cell where project is a null in the DB. I understand why this query does not give me the records where the projectId from table a are null. But I can't find a way to make it happen.

Can anybody help me? Sorry for my imperfect English and a bad title. I didn't really know what to say there.

Upvotes: 0

Views: 56

Answers (1)

Amir Pelled
Amir Pelled

Reputation: 601

If you mean that there are records in table 'a' that do not have a match in table 'c', then change the FROM clause to LEFT JOINS.

example :

SELECT A.PK, B.PK
FROM A
LEFT JOIN B ON a.pk = b.pk

This will bring all the records from table 'A'. For each match on table B, the result set will display (A.pk,B.pk) . For each A.pk that has no match, the result set will display (A.pk,NULL)

Upvotes: 0

Related Questions