如果sql中的参数为null,则返回整个数据

时间:2015-01-21 14:59:27

标签: sql sql-server tsql

我有一个情况,如果我的参数为null,我想从表中选择所有数据,否则它应该根据条件工作,

SELECT 
    CA.ContactAddressId,
    CA.CompanyName AS CompanyName,
    CA.ContactPerson AS ContactPerson,
    CA.Address1 AS Street,
    ISNULL(CA.Address2,'') AS Street2,
    CA.City,
    CA.[State] AS [State],
    CA.Country AS CountryCode,
    CASE
        WHEN CA.Country = 1 THEN 'USA'
        WHEN CA.Country = 2 THEN 'CANADA'
        WHEN CA.Country = 4 THEN 'MEXICO'
    END AS Country,
    CA.ZipCode,
    CA.WorkPhone AS Phone,
    CA.WorkPhoneExt AS Ext,
    ISNULL(CA.Fax,'') AS Fax,
    CA.Email AS [Email],
    CA.AddressType,
    CA.AddressCode,
    CADS.PickupReadyTime AS PickupReadyTime,
    CADS.PickupCloseTime AS PickupCloseTime,
    CADS.DeliveryReadyTime AS DeliveryOpeningTime,
    CADS.DeliveryCloseTime AS DeliveryClosingTime,
    CAST(ISNULL(CAD.ContactAddressId,0) as bit) IsDefault
INTO #ContactAddressDetails
FROM CR2.ContactAddress AS CA WITH (NOLOCK)
INNER JOIN #ContactGroupList list
    ON list.ContactGroupId = CA.ContactGroupId
LEFT JOIN CR2.ContactAddressDefaultSettings AS CADS WITH (NOLOCK)
    ON CADS.ContactAddressId = CA.ContactAddressId
LEFT JOIN CR2.ContactAddressDefault CAD WITH (NOLOCK) 
    ON CAD.ContactAddressId = CA.ContactAddressId 
    AND CAD.UserId = @LoggedInUserId 
    --and CAD.DefaultAddressType = @DefaultAddressType
 WHERE (@ZipCodeOrigin IS Null Or CA.ZipCode IN (@ZipCodeOrigin,@ZipCodeDestination)) 
   AND (@ZipCodeDestination Is Null OR CA.ZipCode IN(@ZipCodeOrigin,@ZipCodeDestination))

@ZipCodeOrigin和@ZipCodeDestination是参数,如果它们为null,我必须从表中获取所有数据。

希望我对我的问题陈述很清楚。

3 个答案:

答案 0 :(得分:3)

如果两个值都不为空,则您的条件会使用相同的条件对数据进行两次过滤。我会这样写:

 WHERE (@ZipCodeOrigin IS NULL AND @ZipCodeDestination IS Null)  OR CA.ZipCode IN (@ZipCodeOrigin, @ZipCodeDestination)) 

答案 1 :(得分:0)

如果您可以选择以编程方式使用简单连接来构建查询,那么当ZipCodeOrigin为null时,就不能连接该条件。

如果你必须坚持使用准备好的语句,解决方案是创建3个更准备好的语句,一个没有ZipCodeOrigin的条件,另一个没有ZipCodeDestination的条件,另一个没有两个条件(并且没有WHERE子句)。

Ahother令人讨厌的解决方案是使用LIKE,如果ZipCodeOrigin为null,则将其设为"%"匹配一切。

答案 2 :(得分:0)

将您的情况改为:

   WHERE CA.ZipCode  = ( Case When @ZipCodeOrigin IS Null Then CA.ZipCode Else                       @ZipCodeOrigin END)
      Or  CA.ZipCode = ( Case When @ZipCodeDestination IS Null Then CA.ZipCode Else @ZipCodeDestination END)