views:

4594

answers:

5

I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:

SELECT Column1, Column2, Column3+Column4 AS [Added Values]
FROM Table

where Column3 or Column4 may be null. In this case, I want null to be considered zero (so 4 + null = 4, null + null = 0).

Any suggestions as to how to accomplish this?

+8  A: 

Since ISNULL in Access is a boolean function (one parameter), use it like this:

SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]
FROM Table
Michael Haren
In access, though, ISNULL is just a boolean function, not a conditional (so it only takes one parameter, and returns whether it's null). Is there a way of doing conditional things in Access?(http://www.techonthenet.com/access/functions/advanced/isnull.php)
Smashery
See my updated answer--untested I'm afraid.
Michael Haren
Yeah, I just found the IIF statement, and it works. Thanks very much!
Smashery
No problem, thanks for correcting my initial answer!
Michael Haren
Personally if you're going to be calling this query a lot then I'd create a view with null replacement already applied. It'll make your code considerably cleaner and apart from striving for elegance clean code is generally less likely to cause maintenance errors later.
Cruachan
+3  A: 

Use the ISNULL replacement command:

 SELECT Column1, Column2, ISNULL(Column3, 0) + ISNULL(Column4, 0) AS [Added Values]FROM Table
jussij
+3  A: 

Use COALESCE.

SELECT 
   Column1, 
   Column2, 
   COALESCE(Column3, 0) + COALESCE(Column4, 0) AS [Added Values]
FROM Table
Walter Mitty
+2  A: 

Even cleaner would be the nz function

nz (column3, 0)
CodeSlave
Note that if you use Nz(), the Nz command is not present in the vba language directly. Normally this has no impact, but if you use linked query in Excel from Access, Nz won't work. But you can still use the iif( isnull()... ) construct.
Knox
A: 

The Nz() function from VBA can be used in your MS Access query.

This function substitute a NULL for the value in the given parameter.

SELECT Column1, Column2, Nz(Column3, 0) + Nz(Column4, 0) AS [Added Values]
FROM Table
Ricardo C