我有一个存储过程,我计划将其用于搜索并获取所有值。
场景: 如果传递的参数是
NULL
,则应返回表中的所有值,如果传递的参数不是NULL
,则应根据LIKE中的条件返回值。
//查询:
ALTER procedure [dbo].[usp_GetAllCustomerDetails]
(
@Keyword nvarchar(20) = null
)
As
Begin
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+'%'
在上面的查询中,当我执行时它不会返回任何值,因为
NULL
被 string
假定为 SQL
,那么我应该在 where
子句中编写什么才能获得所需的输出?
您可以在
where
子句中使用这样的条件
where @Keyword is null or CustomerName like '%' + @Keyword + '%'
我只是想指出解决这个问题的另一种方法。 问题是
@KeyWord
的默认值为 NULL
。 如果将默认值更改为 ''
,那么问题就会消失:
ALTER procedure [dbo].[usp_GetAllCustomerDetails]
(
@Keyword nvarchar(20) = ''
)
任何非 NULL 客户名称都将类似于“%%”。
您只需将
SET @Keyword = coalesce(@Keyword,'')
添加到您的程序中,如下所示:
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+'%'