如何根据参数使用不同的“ where”子句?

时间:2019-12-12 10:53:57

标签: sql-server tsql

使用此示例代码:

CREATE PROCEDURE [dbo].[GetCars] 
    @carModelID UNIQUEIDENTIFIER,   
AS
BEGIN
    SET NOCOUNT ON;

    IF @carModelID IS NULL
    BEGIN
        SELECT *
        FROM dbo.Cars
    END
    ELSE
    BEGIN
        SELECT *
        FROM dbo.Cars
        WHERE ModelID = @carModelID 
          AND Color = 'red'
    END
END
GO

我能以某种方式避免两次输入选择代码并避免BEGIN ELSE吗?像这样...

CREATE PROCEDURE [dbo].[GetCars] 
    @carModelID UNIQUEIDENTIFIER,   
AS
BEGIN
    SET NOCOUNT ON;

    SELECT *
    FROM dbo.Cars
    WHERE
        (Here I need to filter a filter, where it will return all rows, 
         if @carModelID is NULL - and if @carModelID is not null, it must 
         return all rows where cars are red and carModelID equals @carModelID)
END
GO

1 个答案:

答案 0 :(得分:0)

您可以使用它。

SELECT *
        FROM dbo.Cars
        WHERE @carModelID IS NULL 
        OR ( ModelID = @carModelID AND
                      Color = 'red')