5

I would like to create a SP that will return all Country rows unless a CountryID is provided as a parameter. Here is how I imagined it might work, but it doesn't like it.

ALTER PROCEDURE [dbo].[usp_return_countries]
    @CountryID AS INT = 0
AS
BEGIN
        SELECT *
        FROM Countries
        WHERE Active = 1

        IF @CountryID > 0 BEGIN
            AND @CountryID = CountryID
        END

END

Thank you

P.S. I thought there might be a better way than simply repeating the entire SELECT statement based on the said condition.

4 Answers 4

10

Try this, it's elegant :)

 ALTER PROCEDURE [dbo].[usp_return_countries]
   @CountryID AS INT = 0
 AS
 BEGIN

    SELECT *
    FROM Countries
    WHERE Active = 1
    AND (@CountryID = 0 OR @CountryID = CountryID)

 END
Sign up to request clarification or add additional context in comments.

1 Comment

ah yes, of course. I seen this but got confused that it would match the table CountryID as 0. Perfect, thanks
6

Easy enough to wrap up in a single WHERE clause:

SELECT * 
FROM Countries 
WHERE Active = 1 AND (@CountryID = 0 OR CountryID = @CountryID)

Comments

4

Do it like this:

ALTER PROCEDURE [dbo].[usp_return_countries]
    @CountryID AS INT = 0 AS BEGIN

        IF @CountryID > 0 BEGIN
            SELECT *
            FROM Countries
            WHERE Active = 1
            AND @CountryID = CountryID
        END
        ELSE BEGIN
            SELECT *
            FROM Countries
            WHERE Active = 1
        END

END

4 Comments

So even if you have a massive select statement, you would have to repeat the entire thing for a additional condition?
@David this is more readable. If you want, you may choose a more elegant way like the other answers state. But remember, you can repeat the select but only one is really made :P
I did state I wanted something other than repeating the select statement. Thanks anyway.
Your approach may not be 'elegant' but it may produce a better plan.
3

Something like this?

SELECT *
        FROM Countries
        WHERE Active = 1
AND
    (CountryID = @CountryID AND @CountryID <> 0) or (@CountryID = 0)

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.