views:

39

answers:

4

Hi,

I'm trying to do the following:

IF NOT EXISTS ( 
                SELECT  *   
                FROM    [tbl_web_company] 
                WHERE   [name]          = @name
                AND     [address1]      = @address1
                AND     [address2]      = @address2
                AND     [city]          = @city
                AND     [province_id]   = @province_id
                AND     [postal_code]   = @postalcode
                AND     [contact_phone] = @phone
                AND     [contact_fax]   = @fax
                AND     [deleted]       = dbo.pvd_fn_getDeletedDate(@id, @active))
        BEGIN
            SELECT 'update'
        END
        ELSE
        BEGIN
            SELECT 'no update'
        END

I'm basically trying to see if any of the columns have changed, but I'm having problems when @province_id and dbo.pvd_fn_getDeletedDate(@id, @active) are NULL in the database, and are both set as NULL.

Province ID is an INT - Nullable

Deleted is a Datetime - Nullable.

If the record in the database has NULL for both these values, then this will always select 'update'. Which is wrong as [province_id] and [deleted] are NULL.

Any suggestions how to handle NULLS in this case?

+3  A: 

use IS NULL instead = NULL

heximal
Is 'IS NULL' possible though if using parameters instead of hardcoded values?
Adam Witko
i always thought so)
heximal
Is it though? It doesn't work for me. Even if it did, it would only work when the parameter was null (you can't say `if @name is 'John'`). Then there's no point in using a parameter.
Paul Spangle
+2  A: 

Use "IS NULL" instead:

SELECT 'Is null' WHERE NULL = NULL

woudn't return any rows, but:

SELECT 'Is null' WHERE NULL IS NULL

will...

A good reading about nulls here

veljkoz
+2  A: 

As your values are coming from parameters and are not hard coded you can use the following:

...
AND ([province_id] IS NULL OR [province_id] = @province_id)
...

Use the same structure for your other NULLABLE fields.

Tony
+2  A: 

Can you use the ISNULL() function to set a default value?

    SELECT  *   
                FROM    [tbl_web_company] 
                WHERE   [name]          = @name
                AND     [address1]      = @address1
                AND     [address2]      = @address2
                AND     [city]          = @city
                AND     ISNULL([province_id],99999) = ISNULL(@province_id,99999)
                AND     [postal_code]   = @postalcode
                AND     [contact_phone] = @phone
                AND     [contact_fax]   = @fax
                AND     ISNULL([deleted], '1990-01-01') = ISNULL(dbo.pvd_fn_getDeletedDate(@id, @active), '1990-01-01')
    BEGIN
        SELECT 'update'
    END
    ELSE
    BEGIN
        SELECT 'no update'
    END

Using ISNULL() prevents the optimizer from using indexes, so normally I'd advise against this, but the way this query is written, I'd be surprised if it's making use of an index anyway.

Paul Spangle