14

我有一个存储过程,我计划将其用于搜索并获取所有值。

场景: 如果传递的参数是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假定为stringby SQL,那么我应该在where子句中写什么以获得所需的输出?

4

3 回答 3

24

你可以在你的where子句中使用这样的条件

where @Keyword is null or CustomerName like '%' + @Keyword + '%' 
于 2013-09-08T12:16:10.990 回答
4

我只想指出解决这个问题的另一种方法。问题是默认@KeyWord值为NULL. 如果您将默认值更改为'',那么问题就会消失:

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

任何非 NULL 客户名称都将类似于 '%%'。

于 2013-09-08T12:24:28.750 回答
1

您只需要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+'%' 
于 2013-09-08T12:21:31.280 回答