if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[f_split]') and xtype in (n'fn', n'if', n'tf'))drop function [dbo].[f_split]go
/*--得到字符串列表指定位置的字符 可以自定义字符串列表的分隔符 如果取数位置超出的范围,返回空字符串
--邹建 2004.07--*/
/*--调用示例
--测试数据 declare @t table(fitem varchar(100)) insert @t select '100.120.10' union all select '20.140.10' union all select '150.124.150.10' --查询 select fitem1=dbo.f_split(fitem,1,'.') ,fitem2=dbo.f_split(fitem,2,'.') ,fitem3=dbo.f_split(fitem,3,'.') ,fitem4=dbo.f_split(fitem,4,'.') from @t--*/create function f_split(@s varchar(8000), --字符串列表@pos int, --取数位置@splitchar varchar(10) --分隔符)returns varchar(8000)asbegin declare @i int,@ilen int
select @i=charindex(@splitchar,@s),@ilen=len(@splitchar) while @i>0 and @pos>1 select @s=substring(@s,@[email protected],8000) ,@i=charindex(@splitchar,@s) ,@[email protected] return(case @pos when 1 then case when @i>0 then left(@s,@i-1) else @s end else '' end)endgo