[英]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和dbo.pvd_fn_getDeletedDate(@ id,@ active)在数据库中为NULL时,我遇到了问题,并且都设置为NULL。
Province ID is an INT - Nullable 省ID是INT - Nullable
Deleted is a Datetime - Nullable. 已删除是Datetime - Nullable。
If the record in the database has NULL for both these values, then this will always select 'update'. 如果数据库中的记录对这两个值都为NULL,那么这将始终选择“更新”。 Which is wrong as [province_id] and [deleted] are NULL.
哪个是错误的,因为[province_id]和[deleted]是NULL。
Any suggestions how to handle NULLS in this case? 在这种情况下如何处理NULLS的任何建议?
Can you use the ISNULL() function to set a default value? 你能使用ISNULL()函数来设置默认值吗?
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. 使用ISNULL()可以防止优化器使用索引,所以通常我会建议不要这样,但是这个查询的编写方式,如果它正在使用索引,我会感到惊讶。
使用IS NULL代替= NULL
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. 对其他
NULLABLE
字段使用相同的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.