[英]SQL Query with Optional Parameter and Possible Null Column
I am having some difficulty returning all the results I would expect when leaving an optional sql parameter blank on a column that contain null values.当在包含空值的列上将可选的 sql 参数留空时,我在返回我期望的所有结果时遇到了一些困难。
Imagine you have a table with the following (referredby is optional and can therefore be NULL):假设您有一个包含以下内容的表(referredby 是可选的,因此可以为 NULL):
Customertable
ID CustomerName ReferredBy
1 Aaron Joe
2 Peter NULL
3 Steven Joe
Suppose I want to query with an optional SQL parameter for the referredby field like such:假设我想使用一个可选的 SQL 参数查询referredby 字段,如下所示:
declare @referredby as varchar(15)
select id, customername
from customertable<br>
where referredby = isnull(@referredby, referredby)
If I leave the parameter null, this would only return:如果我将参数留空,则只会返回:
1 Aaron 1 亚伦
3 Steven 3 史蒂文
How can I use an optional parameter to return all 3 results?如何使用可选参数返回所有 3 个结果?
Try This:试试这个:
select id, customername
from customertable
where (referredby = @referredby OR @referredby is null)
For reasons explained in this post , comparing null = null
in sql server returns false (or unknown).由于本文中解释的原因,比较 sql server 中的
null = null
返回 false(或未知)。 As does null != null
. null != null
。
If you really like your syntax I believe you could make it work by setting ansi_Nulls to off: set ansi_nulls off
如果你真的喜欢你的语法,我相信你可以通过将 ansi_Nulls 设置为 off 来使它工作:
set ansi_nulls off
Add this line on your query:在您的查询中添加此行:
SELECT ... FROM ... --other codes here
where (referredby = @referredby) OR (@referredby IS NULL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.