LIKE and NULL in WHERE clause in SQL

后端 未结 3 886
闹比i
闹比i 2020-12-18 22:02

I have a store procedure which i have planned to use for search and get all values.

Scenario: If the parameter passed is NULL it should

相关标签:
3条回答
  • 2020-12-18 22:16

    You just need to add SET @Keyword = coalesce(@Keyword,'') to your procedure like this :

     ALTER procedure [dbo].[usp_GetAllCustomerDetails]
    (
    @Keyword nvarchar(20) =  null
    )
    As
    Begin
    SET @Keyword = coalesce(@Keyword,'')
    
    Select CustomerId,CustomerName,CustomerTypeName,CustomerCode,CategoryName,CustomerMobile,CustomerEmail,CustomerAddress,CustomerCity,CustomerState,Pincode
    from tblCustomerMaster CM
    inner join dbo.tblCustomerTypeMaster CTM on CTM.CustomerTypeId = CM.CustomerType
    inner join dbo.tblCategoryMaster CCM on CCM.CategoryId= CM.CustomerCategory
    where CustomerName like '%'+@Keyword+'%' 
    
    0 讨论(0)
  • 2020-12-18 22:26

    You can use condition like this in you where clause

    where @Keyword is null or CustomerName like '%' + @Keyword + '%' 
    
    0 讨论(0)
  • 2020-12-18 22:30

    I just want to point out another way of solving this problem. The issue is that the default value for @KeyWord is NULL. If you change the default to '', then the problem goes away:

    ALTER procedure [dbo].[usp_GetAllCustomerDetails]
    (
    @Keyword nvarchar(20) = ''
    )
    

    Any non-NULL customer name would then be like '%%'.

    0 讨论(0)
提交回复
热议问题