如果SQL Server中的条件为null,则选择所有行

时间:2015-12-08 11:12:24

标签: sql sql-server where-clause

当我在where子句中没有提供任何参数时,我想从临时表中选择所有行。

以下是我的存储过程; #ContactAddressDetails是我的临时表,其中提供了最终数据。 @ZipCodeOrigin@ZipCodeDestination是参数

  • 如果@ZipCodeOrigin = null@ZipCodeDestination = null那么我想获取所有记录,否则只有那些匹配where子句

代码:

CREATE PROCEDURE [CR2].[spGetEmailAddressByZipsTypeahead]       
     @LoggedInUserId BIGINT
     ,@ZipCodeOrigin VARCHAR(10) = NULL      
     ,@ZipCodeDestination VARCHAR(10) = NULL    
     ,@searchText varchar(15)    
AS      
BEGIN      
    DECLARE @OfficeId INT, @AccountId INT      

    CREATE TABLE #ContactGroupList (ContactGroupId INT)      

    SELECT      
        @OfficeId = OfficeId,      
        @AccountId = AccountID      
    FROM CR2.vwAcgUserCustomer WITH (NOLOCK)      
    WHERE UserID = @LoggedInUserId      

    -- Find the all Contact Group associated to the User, his/her Office and Account      
    INSERT INTO #ContactGroupList      
        SELECT ContactGroupId      
        FROM CR2.ContactGroup WITH (NOLOCK)      
        WHERE ((OwnerType = 1 AND OwnerId = @AccountId)      
               OR (OwnerType = 2 AND OwnerId = @OfficeId)      
               OR (OwnerType = 3 AND OwnerId = @LoggedInUserId))      

    --Display all the addresses of the above contact groups.      
    SELECT       
        CA.ContactAddressId,          
        CA.Email AS [Email],      
        CA.AddressType,      
        CA.AddressCode  
    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         
    WHERE 
        CA.ZipCode In  (@ZipCodeOrigin, @ZipCodeDestination)    
        AND CA.Email LIKE @searchText + '%'      
        AND CA.IsDeleted = 0      
        AND CA.AddressType = 3      

    SELECT *      
    FROM #ContactAddressDetails    

    DROP TABLE #ContactAddressDetails      
    DROP TABLE #ContactGroupList      
END

2 个答案:

答案 0 :(得分:2)

如果两个zipcode都为null,您可以使用此谓词不过滤数据:

( (@ZipCodeOrigin is null and @ZipCodeDestination is null) OR CA.ZipCode In (@ZipCodeOrigin, @ZipCodeDestination) )

答案 1 :(得分:2)

替换

map.getFeature(lat, long).setProperty('isColorful', true);

WHERE CA.ZipCode IN (@ZipCodeOrigin, @ZipCodeDestination)

如果WHERE (CA.ZipCode In (@ZipCodeOrigin, @ZipCodeDestination)) OR (@ZipCodeOrigin IS NULL AND @ZipCodeDestination IS NULL) @ZipCodeOrigin都为空,或@ZipCodeDestination与其中一个或两个匹配,则此条件为真。