日期:2014-05-18  浏览次数:20502 次

这个问题比较难,假设用户给定一个参数变量 @categoryId , 要的到属于该categoryId 的所有文章。

文章数据表   (article),   其中有一个字段categoryId   是varchar   类型,存放多个文章分类的ID,代表这篇文章属于多个分类。


下面是一个SQL存储过程,   假设用户给定一个参数变量   @categoryId   ,   要的到属于该categoryId   的所有文章。

declare   @categoryId   varchar(2000)
set   @categoryId   =   '2|8|45|78|4|23 '       --   这个存放的都是分类的ID


要得到所有属于该分类的文章,怎么写SQL     ??  
 
是不是要用   WHILE   循环




------解决方案--------------------
---测试数据
declare @categoryId varchar(2000)
set @categoryId = '2|8|45|78|4|23 '
create table tb(ID int,CgyID int)
insert tb select 1,1
union all select 2,2
union all select 3,8
union all select 4,7
union all select 5,4
union all select 6,2
select * from tb where charindex( '| '+cast(CgyID as varchar)+ '| ', '| '+@categoryId+ '| ')> 0
drop table tb
---结果:
/*
ID CgyID
----------- -----------
2 2
3 8
5 4
6 2
*/