LIKE and NULL in WHERE clause in SQL

别来无恙 提交于 2019-11-29 09:23:42

You can use condition like this in you where clause

where @Keyword is null or CustomerName like '%' + @Keyword + '%' 

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 '%%'.

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+'%' 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!