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
/*--得到字串列表指定位置的字元
可以自訂字串列表的分隔字元
如果取數位置超出的範圍,返回Null 字元串
--鄒建 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)
as
begin
declare @i int,@ilen int
select @i=charindex(@splitchar,@s),@ilen=len(@splitchar)
while @i>0 and @pos>1
select @s=substring(@s,@i+@ilen,8000)
,@i=charindex(@splitchar,@s)
,@pos=@pos-1
return(case @pos when 1
then case when @i>0 then left(@s,@i-1) else @s end
else '' end)
end
go