Suppose I had the following 2 tables:
Table1: Table2:
Col1: Col2: Col3: Col1: Col2: Col
Use Left Outer Join instead of Inner Join to include rows with NULLS.
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 LEFT OUTER JOIN
Table2 ON Table1.Col1 = Table2.Col1
AND Table1.Col2 = Table2.Col2
For more information, see here: http://technet.microsoft.com/en-us/library/ms190409(v=sql.105).aspx
The only correct answer is not to join columns with null values. This can lead to unwanted behaviour very quickly.
e.g. isnull(b.colId,''): What happens if you have empty strings in your data? The join maybe duplicate rows which I guess is not intended in this case.
Try using ISNULL
function:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1
INNER JOIN Table2
ON Table1.Col1 = Table2.Col1
AND ISNULL(Table1.Col2, 'ZZZZ') = ISNULL(Table2.Col2,'ZZZZ')
Where 'ZZZZ'
is some arbitrary value never in the table.
Try using additional condition in join:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1
OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
)
for some reason I couldn't get it to work with the outer join.
So I used:
SELECT * from t1 where not Id in (SELECT DISTINCT t2.id from t2)
Dirty and quick hack:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))