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

kevin_水滴石穿 2011-09-23 04:15:54
在电子商务网站中进行搜索时,经常要将各种条件进行组合查询,如选择了年份,价格,颜色,品牌等条件,要求输出满足条件的结果。我试图写一个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


...全文
70 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
kevin_水滴石穿 2011-09-23
  • 打赏
  • 举报
回复
谢谢了,我明白了
唐诗三百首 2011-09-23
  • 打赏
  • 举报
回复
Sorry, 楼上结尾多了个end, 下次注意.
唐诗三百首 2011-09-23
  • 打赏
  • 举报
回复
用动态SQL实现,例如

create proc [SPname]
@x int=null,
@y int=null,
@z int=null
as
begin
declare @sql varchar(5000)
select @sql='select * from tablename where 1=1 '

if @x is not null
select @sql=@sql+' and x=''' + cast(varchar as @x) + ''' '

if @y is not null
select @sql=@sql+' and y=''' + cast(varchar as @y) + ''' '

if @z is not null
select @sql=@sql+' and z=''' + cast(varchar as @z) + ''' '

exec(@sql)

end


end

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧