Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null value column and NOT EXISTS T-sql

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?

like image 726
adamwtiko Avatar asked Aug 11 '26 05:08

adamwtiko


1 Answers

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.

like image 157
Paul Spangle Avatar answered Aug 13 '26 19:08

Paul Spangle