学院首页>网络编程>其它编程>字符串分拆查询

字符串分拆查询

作者: 来源: 添加时间:2006-5-22 12:05:28
有这样的数据 

字段1字段2 
2,4,23 3,6,345
23,56,43,3,67

取数据的是
查询 字段1中 条件是 4 那么在字段2  在取的是6与 67
结果如下
============
4  6
4  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)
as
begin
 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)
end
go
--查询
declare @a varchar(10)
set @a=’23’ --查询参数
--查询语句
select A=@a,B=dbo.f_value(字段1,字段2,@a)
from tb
go
--删除测试
drop table tb
drop function f_value
/*--测试结果
AB 
---------- ---------- 
23345
233
(所影响的行数为 2 行)
--*/
站内搜索