存储过程中的可选参数问题

时间:2012-12-26 13:52:43

标签: sql-server stored-procedures

我有这个存储过程

ALTER PROCEDURE [dbo].[usp_mySP]
    -- Add the parameters for the stored procedure here
    -- For inventory table check.
    @DealerID       VARCHAR(50),
    @Certified      VARCHAR(50) = NULL,
    -- For fuel value.
    @CityFeatureValue   VARCHAR(50),
    @HwyFeatureValue    VARCHAR(50)

AS
BEGIN
        BEGIN
        SELECT  InventoryID, 
                VIN
        FROM    Inventory
        WHERE   DealerID = @DealerID
                AND Deleted     =   'False'
                AND (IsPending  =   '0'         OR IsPending    IS NULL) 
                --AND (Certified    =   @Certified  OR @Certified   IS NULL)

                AND VIN IN
                        (
                            SELECT      VIN 
                            FROM        FuelPerformance
                            WHERE       (
                                            FeatureTitle = 'Fuel Economy (City)' 
                                            AND FeatureValue = @CityFeatureValue
                                        )
                                        OR 
                                        (
                                            FeatureTitle = 'Fuel Economy (Hwy)' 
                                            AND FeatureValue = @HwyFeatureValue
                                        )
                            GROUP BY    VIN
                            HAVING      COUNT(VIN) > 1
                        )
    END
END

我称之为:

EXEC usp_ListOfVehiclesOnFuelCondition_ForSingleDealer
   '09f5245d' , '', '18', '28'

当我评论该行时

 AND (Certified = @Certified OR @Certified IS NULL)

它正在给出结果,但是当这一行出现时,结果是空白的。

我做错了什么建议?

1 个答案:

答案 0 :(得分:5)

您传入的是一个空字符串('')。这与NULL非常不同。

将参数传递为名为的参数(不含@Certified),或测试空字符串,或传入NULL

命名参数:

EXEC usp_ListOfVehiclesOnFuelCondition_ForSingleDealer @DealerId = '09f5245d',
                                                       @CityFeatureValue = '18', 
                                                       @HwyFeatureValue = '28'

传递NULL

EXEC usp_ListOfVehiclesOnFuelCondition_ForSingleDealer '09f5245d', 
                                                       NULL, 
                                                       '18', 
                                                       '28'

检查''

AND (Certified = @Certified OR @Certified IS NULL OR @Certified = '')