0

Using SQL Server 2008. I have an input param in my stored proc called '@State'. The param can basically be '--All--' or can contain the state to filter.

So, if it is '--All--' I don't want to incorporate the @State into the where clause. Otherwise I'd like it to filter based on the provided @State. So basically it could result in this....

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

or, if they pass '--All--'

SELECT * FROM MyTable
WHERE Type='AAA'

How can I do this in a stored proc?

3 Answers 3

3
SELECT
    *
FROM
    MyTable
WHERE
    Type='AAA'
    AND Status = CASE @Status WHEN '--All--' THEN Status ELSE @Status END
Sign up to request clarification or add additional context in comments.

Comments

1

I thought you made a typo. It should be @State, not @Status. This simple query might not be what you are looking for since you want to two sql statements in your requirement.

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

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.