tags:

views:

58

answers:

2
Snip..
    WHERE     (dbo.ProductIngredients.Ing_EffectiveTo =
                              (SELECT     TOP (1) Ing_EffectiveTo
                                FROM          dbo.ProductIngredients AS ProductIngredients_1
                                WHERE      (Ing_Id = dbo.ProductIngredients.Ing_Id)
                                ORDER BY (CASE WHEN Ing_EffectiveTo IS NULL THEN '01/01/2050' ELSE Ing_EffectiveTo END) DESC))

This works fine is the from the sub where clause is not null, however when null it obviously fails unless I mess with ansi_null settings (which we wont be able to do in next version of sql server so looking for better way). How can I make this query work its like I have to change from = to IS based on the result

+4  A: 

Can't you use ISNULL(Ing_EffectiveTo,'01/01/2050') ?

Arkain
Nope because I dont know weather the value return is NULL or Not, if its not null I want to match against that value..
mattcodes
@mattcodes, If it's null you want it to use '01/01/2050' right?
Arkain
Initially the 01/01/2050 replacement is to ensure that a null value is consider a future data rather than a previous data. but used same technique in coalesce and all well now
mattcodes
okay, but as I understand you ISNULL should be perfect for you. If Ing_EffectiveTo is null then choose the date in the future, otherwise use Ing_EffectiveTo.
Arkain
@Arkain: My understanding is that ISNULL and COALESCE do the same thing, but COALESCE is standard SQL.
Justin K
@Justin K, yes they are similar, but there are some differences: http://databases.aspfaq.com/database/coalesce-vs-isnull-sql.html
Arkain
A: 

Resolved it just wrapped COALESCE around both parts using 01/01/2050. This allows me to use = with NULL - incase where I dont know if value is null or not (and I care about the value if not null) - Legacy DB.

mattcodes
@mattcodes, the `isnull` mentioned in the other answer is exactly what you need.. But you should only use it in the `order by` section
Gaby
Nope, Im interesting in selecting either the latest effective date (which is null) or failing that the most recent date over a set of ingredients. Its not a boolean case of is null or not.
mattcodes
@mattcodes, I still don't understand how isnull can't do this for you, can you give us an example of some data, and what you expect to get back?
Arkain