views:

41

answers:

2

I have a query and I would like to use an IIf function as part of the criteria. Here is the full SQL:

SELECT Hits.HitID, Hits.ListingID, Hits.HitCount, Hits.HitDate, Hits.HitTypeID, Hits.IsDeleted
FROM Hits
WHERE (((Hits.HitDate)>=[Forms]![frmReports]![txtStartDate]) AND ((Hits.IsDeleted)="N"));

Here is the piece of code that causing me anguish:

>=[Forms]![frmReports]![txtStartDate]

If I have a date on frmReports, this will work fine; however, if no date is entered, this returns 0 records (I want it to return ALL records, if this is the case).

How can I make this work?

+2  A: 

Try this:

SELECT Hits.HitID, Hits.ListingID, Hits.HitCount, Hits.HitDate, Hits.HitTypeID, Hits.IsDeleted
FROM Hits
WHERE (((Hits.HitDate)>=nz([Forms]![frmReports]![txtStartDate],"1/1/1")) AND ((Hits.IsDeleted)="N"));

or this

SELECT Hits.HitID, Hits.ListingID, Hits.HitCount, Hits.HitDate, Hits.HitTypeID, Hits.IsDeleted
FROM Hits
WHERE (((Hits.HitDate)>=[Forms]![frmReports]![txtStartDate]) AND ((Hits.IsDeleted)="N"))
    OR (([Forms]![frmReports]![txtStartDate] = "") AND (Hits.IsDeleted="N"));
Andrew Cooper
The second option didn't work, but the first one sure did! Thank you very much!
Robert
`[Forms]![frmReports]![txtStartDate] = ""` should be replaced with `[Forms]![frmReports]![txtStartDate] Is Null`.
David-W-Fenton
A: 

if no date is entered, this returns 0 records (I want it to return ALL records, if this is the case)

SELECT
    h.HitID,
    h.ListingID,
    h.HitCount,
    h.HitDate,
    h.HitTypeID,
    h.IsDeleted
FROM
    Hits AS h
WHERE
    (h.HitDate>=[Forms]![frmReports]![txtStartDate]
        AND h.IsDeleted="N")
    Or [Forms]![frmReports]![txtStartDate] Is Null;

If you meant all records where IsDeleted="N" when no value entered for txtStartDate, change the WHERE clause to this:

WHERE
    h.IsDeleted="N"
    And (h.HitDate>=[Forms]![frmReports]![txtStartDate]
    Or [Forms]![frmReports]![txtStartDate] Is Null);
HansUp
The parentheses are really important there to insure the AND and OR operators are executed in the right order.
David-W-Fenton