SQL Server字符串切割函数
程序员文章站
2023-12-13 16:25:40
复制代码 代码如下: create function fgetstrbysplit ( @source varchar(max), @index int, @splitch...
复制代码 代码如下:
create function fgetstrbysplit
(
@source varchar(max),
@index int,
@splitchar varchar(1)
)
returns varchar(max)
as
begin
declare @len int
declare @n int = 0
declare @chindex int
declare @result varchar(max)
--获取总长度
set @len = len(@source)
--获取切割字符位置
set @chindex = charindex(@splitchar,@source)
while @chindex > 0
begin
if(@n = @index)
begin
set @source = substring(@source,0,@chindex)
break
end
set @source = substring(@source,@chindex+1,@len)
set @chindex = charindex(@splitchar,@source)
set @len = len(@source)
set @n = @n + 1
end
return @source
end
go
--调用
declare @value varchar(max)
set @value = dbo.fgetstrbysplit('645002*01_45854_183677_12',0,'_')
print @value
结果:
645002*01
--1
45854
--2
183677