TSQL 定义分割字符串的函数
一、按指定符號分割字符串,返回分割后的元素個數,方法很簡單,就是看字符串中存在多少個分隔符號,然后再加一,就是要求的結果。
CREATEfunctionGet_StrArrayLength
(
@strvarchar(1024),--要分割的字符串
@splitvarchar(10)--分隔符號
)
returnsint
as
begin
declare@locationint
declare@startint
declare@lengthint
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
調用示例:selectdbo.Get_StrArrayLength('78,1,2,3',',')
返回值:4
二、按指定符號分割字符串,返回分割后指定索引的第幾個元素,象數組一樣方便
CREATEfunctionGet_StrArrayStrOfIndex
(
@strvarchar(1024),--要分割的字符串
@splitvarchar(10),--分隔符號
@indexint--取第幾個元素
)
returnsvarchar(1024)
as
begin
declare@locationint
declare@startint
declare@nextint
declare@seedint
set@str=ltrim(rtrim(@str))
set@start=1
set@next=1
set@seed=len(@split)
set@location=charindex(@split,@str)
while@location<>0and@index>@next
begin
set@start=@location+@seed
set@location=charindex(@split,@str,@start)
set@next=@next+1
end
if@location=0select@location=len(@str)+1
--這兒存在兩種情況:1、字符串不存在分隔符號2、字符串中存在分隔符號,跳出while循環后,@location為0,那默認為字符串后邊有一個分隔符號。
returnsubstring(@str,@start,@location-@start)
end
調用示例:selectdbo.Get_StrArrayStrOfIndex('8,9,4',',',2)
返回值:9
三、結合上邊兩個函數,象數組一樣遍歷字符串中的元素
createfunctionf_splitstr(@SourceSqlvarchar(8000),@StrSepratevarchar(100))
returns@temptable(F1varchar(100))
as
begin
declare@chasvarchar(100)
set@SourceSql=@SourceSql+@StrSeprate
while(@SourceSql<>'')
begin
set@ch=left(@SourceSql,charindex(',',@SourceSql,1)-1)
insert@tempvalues(@ch)
set@SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'')
end
return
end
----調用
select*fromdbo.f_splitstr('1,2,3,4',',')
--結果:
1
2
3
4
總結
以上是生活随笔為你收集整理的TSQL 定义分割字符串的函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: INDEL的重新比对和碱基质量分数的重新
- 下一篇: 合并ts文件