开发者

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?


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.


use IS NULL instead = NULL


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜