SQL - 条件 WHERE 子句 [英] SQL - Conditional WHERE clause

查看:50
本文介绍了SQL - 条件 WHERE 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行查询的 SQL Server 2005 存储过程.这个存储过程接受三个参数.参数如下:

I have a SQL Server 2005 stored procedure that performs a query. This stored procedure takes in three parameters. The parameters are as follows:

@StateID as int,
@CountyID 作为 int,
@CityID 作为 int

@StateID as int,
@CountyID as int,
@CityID as int

这些参数用于查询客户列表.如果参数值不为空,我想基本上做一个AND".但是,此时我无法执行 if-else.如果参数值不为空,如何添加这些子句.换句话说:

These parameters are used to query a list of customers. I want to basically do a "AND" if the parameter value is not null. However, I cannot do an if-else at this time. How do I add these clauses if the parameter value is not null. In other words:

SELECT
  *
FROM
  Customer c
WHERE
 c.StateID=@StateID 
 -- AND c.CountyID=@CountyID IF @CountyID IS NOT NULL
 -- AND c.CityID=@CityID IF @CityID IS NOT NULL

推荐答案

将它们与一些 OR 语句结合起来:

Couple those with some OR statements:

SELECT *
FROM
    Customer c
WHERE
    c.StateID=@StateID
    AND ( c.CountyID=@CountyID OR @CountyID IS NULL )
    AND ( c.CityID=@CityID OR @CityID IS NULL )

对于这些参数中的每一个,如果它为空,那么检查基本上被忽略.

For each of those parameters, if it is null, then the check is basically ignored.

这篇关于SQL - 条件 WHERE 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆