【问题标题】:SQL Server WHERE clause based on conditions基于条件的 SQL Server WHERE 子句
【发布时间】:2019-12-18 05:29:54
【问题描述】:

我有一个 SQL Server 查询,我想为 @catid、@factor 和 @title1 添加 where 子句,如果它们都不为 null 或为零。

不想让我的代码混乱。例如,如果 @catid 为 null,则条件 catid=@catid 将从 where 中省略,结果如下:

where catid = @catid 
  and factorid = @factor 
  and description = @title1

对于其他 @factor 和 @title1 参数也是如此。

有什么想法吗?

这是主要代码:

select @countoffset = count(*) 
from acchesab ac
inner join accusrhesab ach on ac.accid = ach.id
inner join accdoc acd on acd.id = ac.docid
where catid = @catid 
  and factorid = @factor 
  and description = @title1

【问题讨论】:

标签: sql-server tsql conditional-statements where-clause


【解决方案1】:

试试下面的脚本。这将检查值是否为 NULL 列或等于提供的值。两种情况都会返回 TRUE。

select @countoffset=count(*) from acchesab ac
inner join accusrhesab ach on ac.accid=ach.id
inner join accdoc acd on acd.id=ac.docid
where 
(catid=@catid OR catid IS NULL)  
and (factorid=@factor OR factorid IS NULL) 
and (description=@title1 OR description IS NULL) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多