日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

T-SQL像数组一样处理字符串、分割字符串,遍历数组

發布時間:2023/12/10 数据库 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 T-SQL像数组一样处理字符串、分割字符串,遍历数组 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

T-SQL對字符串的處理能力比較弱,比如我要循環遍歷象1,2,3,4,5這樣的字符串,如果用數組的話,遍歷很簡單,但是T-SQL不支持數組,所以處理下來比較麻煩。下邊的函數,實現了象數組一樣去處理字符串。 一、按指定符號分割字符串,返回分割后的元素個數,方法很簡單,就是看字符串中存在多少個分隔符號,然后再加一,就是要求的結果。

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',',')

返回值:4

二、按指定符號分割字符串,返回分割后指定索引的第幾個元素,象數組一樣方便

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

if @location =0 select @location =len(@str)+1

?--這兒存在兩種情況:1、字符串不存在分隔符號 2、字符串中存在分隔符號,跳出while循環后,@location為0,那默認為字符串后邊有一個分隔符號。

return substring(@str,@start,@location-@start)

end

?調用示例:select dbo.Get_StrArrayStrOfIndex('8,9,4',',',2) 返回值:9

三、結合上邊兩個函數,象數組一樣遍歷字符串中的元素

declare @str varchar(50)

set @str='1,2,3,4,5'

declare @next int

set @next=1

while @next<=dbo.Get_StrArrayLength(@str,',')

begin

print dbo.Get_StrArrayStrOfIndex(@str,',',@next)

set @next=@next+1

end

調用結果: 1 2 3 4 5

?

引文來源??T-SQL象數組一樣處理字符串、分割字符串,遍歷數組 - bloodycool - 博客園

總結

以上是生活随笔為你收集整理的T-SQL像数组一样处理字符串、分割字符串,遍历数组的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。