条件WHERE语句SQL Server

时间:2012-02-02 10:32:14

标签: sql sql-server-2008 tsql

我想创建一个返回所有Country行的SP,除非提供CountryID作为参数。这是我想象它可能会起作用的方式,但它不喜欢它。

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

谢谢

P.S。我认为可能有一种更好的方法,而不是简单地根据上述条件重复整个SELECT语句。

4 个答案:

答案 0 :(得分:9)

试试这个,它很优雅:)

 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

答案 1 :(得分:5)

很容易包含在单个WHERE子句中:

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

答案 2 :(得分:4)

这样做:

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

答案 3 :(得分:2)

这样的东西?

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