【问题标题】:SQL Query with Optional Parameter and Possible Null Column带有可选参数和可能的空列的 SQL 查询
【发布时间】:2012-06-18 23:40:31
【问题描述】:

当在包含空值的列上将可选的 sql 参数留空时,我在返回我期望的所有结果时遇到了一些困难。

假设您有一个包含以下内容的表(referredby 是可选的,因此可以为 NULL):

Customertable
ID    CustomerName  ReferredBy
1      Aaron         Joe
2      Peter         NULL
3      Steven        Joe

假设我想用一个可选的 SQL 参数查询被引用的字段,如下所示:

declare @referredby as varchar(15)

select id, customername
from customertable<br>
where referredby = isnull(@referredby, referredby)

如果我将参数保留为空,则只会返回:
1 亚伦
3史蒂文

如何使用可选参数返回所有 3 个结果?

【问题讨论】:

    标签: sql tsql sql-server-2005


    【解决方案1】:

    试试这个:

    select id, customername
    from customertable
    where (referredby = @referredby OR @referredby is null)
    

    由于explained in this post 的原因,在 sql server 中比较 null = null 返回 false(或未知)。 null != null 也是如此。

    如果您真的喜欢您的语法,我相信您可以通过将 ansi_Nulls 设置为 off 来使其工作:set ansi_nulls off

    【讨论】:

    • 啊,根据我的阅读,我认为您使用的语法和 isnull()... 语法是可以互换的
    • 不,重要的是要知道 IS NULLISNULL() 在 SQL Server 中做的事情非常不同。如果您不熟悉两者之间的区别,可能会造成混淆。
    【解决方案2】:

    在您的查询中添加这一行:

    SELECT ... FROM ... --other codes here
    where (referredby = @referredby) OR (@referredby IS NULL)
    

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 2017-11-29
      • 2014-10-05
      • 2018-01-04
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多