如果在SQL IN运算符中字符串为空,则选择所有数据

伊格索尼

我的网站上有一个用于产品过滤器的存储过程,如下所示:

ALTER PROCEDURE [dbo].[sp_product_get_by_filters]
    (@brand_names nvarchar(max),
     @type nvarchar(max))
AS
BEGIN
    SELECT     
        tbl_product.product_code, 
        tbl_product.brand_name, 
        tbl_product.subcategory_code, 
        tbl_product.product_name, 
        tbl_product.product_photo_1,
        tbl_product.filter_code, 
        (select filter_name from tbl_filter where filter_code =  tbl_product.filter_code )as filter_name,
        (select AVG(CAST(rating AS DECIMAL(10,2))) from tbl_review where product_code = tbl_product.product_code) as Rating,
        (select TOP 1 sub_product_price from tbl_sub_product where product_code = tbl_product.product_code) as product_price,
        (select TOP 1 size from tbl_sub_product where product_code = tbl_product.product_code) as size,
        (select TOP 1 sub_product_code from tbl_sub_product where  product_code = tbl_product.product_code) as sub_product_code
    FROM  
        tbl_product 
    WHERE 
        tbl_product.brand_name IN (SELECT * FROM dbo.splitstring(@brand_names)) 
        AND tbl_product.filter_code IN (SELECT * FROM dbo.splitstring(@type)) 
END

@brand_names 这是例如用逗号分隔的品牌名称的字符串

Apple,Samsung,Nokia

并且@type是作为喜欢的产品的过滤器

 'Watch,Mobile,Tablet'

dbo.splitstring函数从连接的字符串中分离出每个值,并将列表作为表格返回。因此,当用户同时选择“品牌名称”和“类型”时,查询将返回值,但如果用户仅选择“品牌名称”或“类型”,则查询将不会返回任何值。如果用户同时选择“品牌名称”和“类型”或未选择任何一种产品(我想像每个电子商务网站中的过滤器一样),我想让查询返回产品。如果用户未选择任何过滤器,那么我将在变量中传递一个空字符串,例如,如果用户未选择任何品牌,则@brand_names将为@brand_names = ''

例如,如果用户选择“ Apple品牌”,则查询必须返回与此品牌相关的所有产品。再次,如果用户选择Type手表,则查询必须返回Apple品牌的Watches。我正在使用SQL Server 2008。

感谢您的帮助。

Allmhuran

对于这种“可选参数”查询,option recompile最终可以大大提高性能。

如果“未选定”参数是空字符串,则可以执行以下操作:

WHERE 
   (@brand_names = '' or tbl_product.brand_name IN (SELECT * from dbo.splitstring(@brand_names)))
   and (@type = '' or tbl_product.filter_code IN (SELECT * from dbo.splitstring(@type)))
option (recompile)

option (recompile)告诉SQL每次都要建立一个新的计划,这条语句的程序运行。因此,例如,如果您为传递了一个空字符串@brand_names,则引擎甚至不需要评估该or tbl_product.brand_name in ...谓词一部分。如果您不这样做,那么SQL将像往常一样为第一个执行建立计划,然后在后续执行中重用该计划。当不同的参数值可以对结果产生如此大的影响时,这不是很好。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章