我想创建一个SP,它将返回所有Country行,除非提供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语句更好的方法。

最佳答案

试试这个,很优雅:)

 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

关于sql - 条件WHERE语句SQL Server,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9110784/

10-12 01:07