简体   繁体   English

带有可选参数和可能的空列的 SQL 查询

[英]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.

相关问题 检查 NULL 时,SQL 查询中的可选参数非常慢 - Optional parameter in SQL query very slow when checking for NULL SQL查询使用同一列上的3个可选参数过滤数据 - SQL query to filter data with 3 optional Parameter on same Column sql查询参数是否为空 - sql query if parameter is null 如何在 SQL 服务器中包含可选的 Null 参数 - How To Include An Optional Null Parameter In SQL Server 如何在SQL查询中设置动态的可选WHERE子句? (如果参数的值不为空) - How can I set dynamic optional WHERE clauses into a SQL query? (if the value of the parameter is not null) 是否可以在单个查询中选择“可选”列? - Is it possible selecting “optional” column in single query? (ISNULL(@parameter) OR @parameter &gt; Column) 模式的 SQL 查询优化器以及它是否针对 @parameter 为空时进行优化 - SQL query optimiser for (ISNULL(@parameter) OR @parameter > Column) patterns and whether it optimises for when @parameter is null 具有可能为空参数的SQL查询 - SQL Query with possible null parameters IS NULL的可选参数查询在Java Sqlite中无法按预期工作 - Optional Parameter query with IS NULL not working as expected in Java Sqlite 处理查询中具有空值的可选参数的最佳方法 - Best way to handle optional parameter with null value in query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM