Split函数(SQL Server)
-- 建立函数
create function dbo.fn_split
(
@originalString nvarchar(200),
@splitter nvarchar(1)
)
returns @temp table
(
id int identity(1, 1) primary key,
value nvarchar(100)
)
as
begin
declare @i int, @tempString varchar(100)
set @originalString=rtrim(ltrim(@originalString))
set @i=charindex(@splitter, @originalString )
while @i > 0
begin
set @tempString=left(@originalString, @i-1)
if(len(@tempString)=1)
set @tempString='00'+ @tempString
if(len(@tempString)=2)
set @tempString='0'+ @tempString
insert @temp values(@tempString)
set @originalString=substring(@originalString, @i+1, len(@originalString)-@i)
set @i=charindex(@splitter, @originalString )
end
if @originalString <> ''
insert into @temp(value) values (@originalString)
return
end
go
-- 调用
select * from dbo.fn_split('10.162.146.168', '.')
-- 执行结果
id value
----------- ------------
1 010
2 162
3 146
4 168
(4 row(s) affected)
-- 删除函数
drop function dbo.fn_split