I have this SQL query in Access, which works fine:
SELECT TableA.FieldA As [Code],
Count(TableA.FieldC) AS [Count]
FROM ((MainTable)
LEFT JOIN TableA ON MainTable.FieldB = TableA.FieldB)
WHERE (((MainTable.DateOf)>=#1/1/2012#))
AND Clng(TableA.FieldA) >= 119593451
AND Clng(TableA.FieldA) <= 119593461
GROUP BY TableA.FieldA;
But when I try another left join, like so:
SELECT TableA.FieldA As [Code],
Count(TableA.FieldC) AS [Count]
FROM ((MainTable)
LEFT JOIN TableA ON MainTable.FieldB = TableA.FieldB)
LEFT JOIN TableB ON TableA.FieldD = TableB.FieldD
WHERE (((MainTable.DateOf)>=#1/1/2012#))
AND Clng(TableA.FieldA) >= 119593451
AND Clng(TableA.FieldA) <= 119593461
GROUP BY TableA.FieldA;
I am using the parenthesis in the FROM claused based on this: http://nm1m.blogspot.com/2007/10/multiple-left-joins-in-ms-access.html
It gives the error Invalid use of Null, which doesn’t make sense to me as I’m performing no null check etc. What is the problem here? I’m trying to pull a field in TableB to display (but did not put it in the select section yet).
Access likes its parentheses. Add more parentheses around joins.
The
CLngfunction requires a non-null value. You can fix this withCLng(Nz(TableA.FieldA, "0")) >= 119593451. Though, if the field is numeric, why on earth would you make it text to begin with? This is a serious problem that I highly recommend fixing immediately (if at all possible) by changing the data type to a numeric one.But you have another problem. It is meaningless to
LEFT JOINto a table if you then in theWHEREclause put a condition, as you are doing in your query! Either change to anINNER JOINor put your conditions onTableAinto theONclause of theLEFT JOIN. If Access won’t allow this syntax, then change to a derived table:Note: adding
WHERE TableA.FieldA IS NOT NULLmay work but may not work. In Access it could be 100% safe but such a query in SQL Server would NOT be safe because there is no guaranteeing the order of conditions being applied. Obviously, in SQL Server you can convert to an integer even when NULL and there is noCLngfunction, but the point is still valid: do not get in the habit of relying on some imagined order ofWHEREconditions protecting you from invalid type conversion: instead you must handle the invalid type conversion inside the expression that can error–that is best practice.