-- 按指定符号分割字符串,返回分割后的元素个数
create function Get_StrArrayLength(
@str varchar ( 1024 ), -- 分割字符串
@split varchar ( 10 ) -- 分割符号
)
returns int
as
begin
declare @location int
declare @start int
declare @length int
set @str = ltrim ( rtrim ( @str ))
set @location = charindex ( @split , @str ) -- 返回字符串中指定表达式的起始位置
set @length = 1
while @location <> 0
begin
set @start = @location + 1
set @location = charindex ( @split , @str , @start )
set @length = @length + 1
end
return @length
end
调用示例: select dbo.Get_StrArrayLength('78,1,2,3',',')
--
按指定符号分割字符串,返回分割后指定索引的第几个元素
create function Get_StrArrayStrOfIndex(
@str varchar ( 1024 ), -- 要分割的字符串
@split varchar ( 10 ), -- 分割符号
@index int -- 取第几个元素
)
returns varchar ( 1024 )
as
begin
declare @location int -- 定位点
declare @start int -- 起始位置
declare @next int -- 下一个位置
declare @seed int -- 分隔符长度
set @str = ltrim ( rtrim ( @str ))
set @start = 1
set @next = 1
set @seed = len ( @split ) -- 取得分隔符长度
set @location = charindex ( @split , @str )
while @location <> 0 and @index > @next
begin
set @start = @location + @seed
set @location = charindex ( @split , @str , @start )
set @next = @next + 1
end
-- 这儿存在两种情况:1、字符串不存在分割符号
-- 2、字符串存在分隔符,跳出while循环后,@location为0,那默认为字符串后边有个分割符号。
if @location = 0 select @location = len ( @str ) + 1
return substring ( @str , @start , @location - @start )
end
create function Get_StrArrayStrOfIndex(
@str varchar ( 1024 ), -- 要分割的字符串
@split varchar ( 10 ), -- 分割符号
@index int -- 取第几个元素
)
returns varchar ( 1024 )
as
begin
declare @location int -- 定位点
declare @start int -- 起始位置
declare @next int -- 下一个位置
declare @seed int -- 分隔符长度
set @str = ltrim ( rtrim ( @str ))
set @start = 1
set @next = 1
set @seed = len ( @split ) -- 取得分隔符长度
set @location = charindex ( @split , @str )
while @location <> 0 and @index > @next
begin
set @start = @location + @seed
set @location = charindex ( @split , @str , @start )
set @next = @next + 1
end
-- 这儿存在两种情况:1、字符串不存在分割符号
-- 2、字符串存在分隔符,跳出while循环后,@location为0,那默认为字符串后边有个分割符号。
if @location = 0 select @location = len ( @str ) + 1
return substring ( @str , @start , @location - @start )
end
调用示例:select dbo.Get_StrArrayStrOfIndex('8,9,4',',',4)