sql獲取數組指定元素


需求:獲取字符數組1,2,3的第2個元素

方法:通過自定義函數來實現

/*
       獲取字符串數組某個元素
*/
if exists (select 1 from sysobjects where id = object_id('Get_StrArrayStrOfIndex' ))
   drop Function Get_StrArrayStrOfIndex
go
create function Get_StrArrayStrOfIndex
(
  @str varchar(5000 ),   -- 要分割的字符串
  @split varchar(10 ),   -- 分隔符號
  @index int                   --取第幾個元素
)
returns varchar (5000)
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
            
       return substring (@str, @start,@location -@start)
end
GO

用法:

print dbo.Get_StrArrayStrOfIndex('1,2,3',',',2)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM