SELECT Asset.AssetID, AnsMaint.Answer, Convert(datetime, AnsMaint.Answer) as maintasdate
FROM Asset INNER JOIN
AssetAnswer AnsMaint ON AnsMaint.AssetID = Asset.AssetID INNER JOIN
AssetField FldMaint ON FldMaint.AssetFieldID = AnsMaint.AssetFieldID
WHERE FldMaint.FieldText = 'Maint. Agreement Term'
AND ISDATE(AnsMaint.Answer) = 1
AND Convert(datetime, AnsMaint.Answer) < DateAdd(d, 145, GetDate())
I get the error on the last part of the AND. If I comment the AND out, it works fine. My dates in the DB happen to be 10/10/2012 and are valid. IsDate should weed out anything that is not valid.
In DB the results (when I comment out the last line). I'm completely stumped.
106 10/10/2012 2012-10-10 00:00:00.000
115 10/10/2012 2012-10-10 00:00:00.000
MORE interesting tidbits. If I change the last AND line to
AND DateAdd(d, cast(Asset.MaintenanceFreq as int), Convert(datetime, AnsMaint.Answer)) < DateAdd(d, 45, GetDate())
it works. If I take out the 2nd parameter (the cast as int) and replace it with a number or a zero, it gives me the same error.
I'm stumped. Any help would be so much appreciated!
Oh, AssetMaint.Answer is a varchar field in the DB nothing I can do about that.
ISDATE()'weeding out' non-date values - SQL doesn't really do short-circuit logic like imperative languages; the optimizer is allowed to rearrange things as it sees fit.