电子商务中遇到组合搜索的问题

         在电子商务网站中进行搜索时,经常要将各种条件进行组合查询,如选择了年份,价格,颜色,品牌等条件,要求输出满足条件的结果。我试图写一个SQL函数来实现这种动态组合的查询,但是还是没有能完全实现,只是能实现固定的2中组合的查询,希望各位大侠看到下面代码后能够帮忙实现下或者提供下思路:

        /*根据字符串中的分隔符,将字符分割成一个列表,通过Table返回  */
create function [dbo].[fn_split](@inputstr nvarchar(4000), @seprator nvarchar(10))
returns @temp table (a nvarchar(200))
as
begin
  declare @i int
  set @inputstr = rtrim(ltrim(@inputstr))
  set @i = charindex(@seprator , @inputstr)
  while @i >= 1
  begin
    insert @temp values(left(@inputstr , @i - 1))
    set @inputstr = substring(@inputstr , @i + 1 , len(@inputstr) - @i)
    set @i = charindex(@seprator , @inputstr)
  end
  if @inputstr <> '\'
  insert @temp values(@inputstr)
  return
end

 

/*解析输入的字符串中的分隔符来获取搜索条件,
同时根据这些搜索条件在表T_B_ProductAttr中进行查询
目前函数只是实现了查询2个或者3个条件组成字符串的功能
我花了2个小时试图完成能将字符串分解成n个条件的查询,结果
未果,希望各位大侠能帮忙扩展成能将字符串分解成n个条件的查询
 */
CREATE function [dbo].[fn_GetProductIDByAttValue]
(
 @attval nvarchar(200),--输入条件字符
@num int--条件属性的个数
)
returns @temp table (a nvarchar(200))
as
begin
 --declare @temp table(a nvarchar(200))
 --声明临时表来存放输入的条件值
 declare @tempAttValue table(rownum int,a nvarchar(200))
 --将条件值存放在临时表并加上行号
 insert into @tempAttValue
 select  ROW_NUMBER() Over (ORDER BY a),a 
 from dbo.fn_split(@attval,',')
 --如果条件的个数为2
 if @num=2
 begin
  --声明属性参数并给其赋值
  declare @attval1 nvarchar(30)
  declare @attval2 nvarchar(30)
  select @attval1=a from @tempAttValue
  where rownum=1
  select @attval2=a from @tempAttValue
  where rownum=2
  --获取查询到的结果并返回
  insert into @temp
  select ProductID from T_B_ProductAttr
  where
attrValue=@attval1 and ProductID in (
  select ProductID from T_B_ProductAttr
  where
attrValue=@attval2)
 end
 else if @num=3 
 begin
  --声明属性参数并给其赋值
  declare @attval4 nvarchar(30)
  declare @attval5 nvarchar(30)
  declare @attval6 nvarchar(30)
  select @attval4=a from @tempAttValue
  where rownum=1
  select @attval5=a from @tempAttValue
  where rownum=2
  select @attval6=a from @tempAttValue
  where rownum=3
  --获取查询到的结果并返回
  insert into @temp
  select ProductID from T_B_ProductAttr
  where
attrValue=@attval4 and ProductID in (
  select ProductID from T_B_ProductAttr
  where
attrValue=@attval5 and ProductID in (
  select ProductID from T_B_ProductAttr
  where
attrValue=@attval6
  ))
 end
 return
end

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值