Sentencia WHERE condicional SQL Server

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

Gracias

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

preguntado el 02 de febrero de 12 a las 10:02

4 Respuestas

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

Respondido 02 Feb 12, 14:02

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

Easy enough to wrap up in a single WHERE cláusula:

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

Respondido 02 Feb 12, 14:02

Hazlo asi:

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

Respondido 02 Feb 12, 17:02

So even if you have a massive select statement, you would have to repeat the entire thing for a additional condition? - David

@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 - aF.

I did state I wanted something other than repeating the select statement. Thanks anyway. - David

Your approach may not be 'elegant' but it may produce a better plan. - un día cuando

¿Algo como esto?

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

Respondido 02 Feb 12, 14:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.