简体   繁体   English

T-SQL:WHERE子句-如何根据输入变量进行调整

[英]T-SQL: WHERE Clause - How to adjust based on input variable

Using SQL Server 2008. I have an input param in my stored proc called '@State'. 使用SQL Server2008。我的存储过程中有一个输入参数,称为“ @State”。 The param can basically be '--All--' or can contain the state to filter. 参数基本上可以是“ --All--”,也可以包含要过滤的状态。

So, if it is '--All--' I don't want to incorporate the @State into the where clause. 因此,如果它是“ --All--”,我不想将@State合并到where子句中。 Otherwise I'd like it to filter based on the provided @State. 否则,我希望它根据提供的@State进行过滤。 So basically it could result in this.... 因此基本上可以导致此...

SELECT * FROM MyTable
WHERE Type='AAA' AND Status=@Status

or, if they pass '--All--' 或者,如果他们通过“ --All--”

SELECT * FROM MyTable
WHERE Type='AAA'

How can I do this in a stored proc? 如何在存储的过程中执行此操作?

SELECT
    *
FROM
    MyTable
WHERE
    Type='AAA'
    AND Status = CASE @Status WHEN '--All--' THEN Status ELSE @Status END

I thought you made a typo. 我以为你打错字了。 It should be @State, not @Status. 它应该是@State,而不是@Status。 This simple query might not be what you are looking for since you want to two sql statements in your requirement. 这个简单的查询可能不是您要查找的内容,因为您需要两个sql语句。

SELECT * FROM MyTable
WHERE Type='AAA' AND (@State='--All--' or State=@State)

Or... 要么...

you could make it even simpler than that: 您可以将其简化为:

 SELECT * FROM MyTable
 WHERE Type='AAA' AND @State in ('--All--', State)

No need to do it in a stored procedure, unless absolutely necessary (or if business/coding practice requires you to do so). 除非绝对必要(或者如果业务/编码实践要求您这样做),则无需在存储过程中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM