字符串分拆查询

日期:2006-03-29

原帖地址:http://community.csdn.net/Expert/topic/3230/3230422.xml?temp=.7884485

有这样的数据

字段1      字段2  2,4,23    3,6,345 23,56,4   3,3,67取数据的是查询 字段1中 条件是 4 那么在字段2  在取的是6与 67结果如下============4     64     67

-------------------------------------------------------------------------------

--处理示例

--测试数据create table tb(字段1 varchar(10),字段2 varchar(10))insert tb select '2,4,23' ,'3,6,345'union all select '23,56,4','3,3,67'go

--写个自定义函数来处理create function f_value(@a varchar(10),@b varchar(10),@c varchar(10))returns varchar(10)asbegin declare @i int,@pos int  select @a=left(@a,charindex(','+@c+',',','+@a+',')-1)  ,@pos=len(@a)-len(replace(@a,',',''))+1  ,@i=charindex(',',@b)

 while @i>0 and @pos>1  select @b=substring(@b,@i+1,8000)   ,@i=charindex(',',@b)   ,@pos=@pos-1 return(case @pos when 1    then case when @i>0 then left(@b,@i-1) else @b end   else '' end)endgo

--查询declare @a varchar(10)set @a='23' --查询参数

--查询语句select A=@a,B=dbo.f_value(字段1,字段2,@a)from tbgo

--删除测试drop table tbdrop function f_value

/*--测试结果

A          B          ---------- ---------- 23         34523         3

(所影响的行数为 2 行)--*/

责任编辑:H.R.M
Link partners: You Book Case LAMP Spot - Linux Apache MySQL PHP Spot