作业帮 > 综合 > 作业

SQL语句 怎么获取第一个逗号到第二个逗号之间或者第二个逗号到第三个逗号之间的字符串

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/28 15:08:27
SQL语句 怎么获取第一个逗号到第二个逗号之间或者第二个逗号到第三个逗号之间的字符串
比如‘abcd,1234,ABCD,efg’获取 1234或者ABCD
还有‘abcd,1234,ABCD,5678’ 获得5678的
Create FUNCTION [dbo].UFN_SubIndex
 (
 @p_value nvarchar(100),
 @p_split nvarchar(1)=',',
 @p_index int
 )  
RETURNS nvarchar(50)
AS
Begin 
  DECLARE @CurrentIndex int;
  DECLARE @Length int;
     DECLARE @NextIndex int;
     DECLARE @ReturnText nvarchar(50);
     
     Set @CurrentIndex=1;
     Set @NextIndex=@p_index
     Set @Length=LEN(@p_value)
     if @p_index<0
        set @p_index=0;
     
     WHILE(@CurrentIndex<=@Length and @p_index>=0)
         BEGIN
             set @NextIndex=charindex(@p_split,@p_value,@CurrentIndex);
             set @p_index =@p_index-1;
             IF(@NextIndex=0 OR @NextIndex IS NULL)
    Begin
                 set @NextIndex=@Length+1;
                 set @ReturnText=substring(@p_value,@CurrentIndex,@NextIndex-@CurrentIndex);
                 set @CurrentIndex=@NextIndex+1;
                End
             Else
               Begin
                 set @NextIndex=@NextIndex;
                 set @ReturnText=substring(@p_value,@CurrentIndex,@NextIndex-@CurrentIndex);
                 set @CurrentIndex=@NextIndex+1;
               End
           END
     RETURN @ReturnText;
 
End
GO
select dbo.UFN_SubIndex('abcd,1234,ABCD,efg', ',', 2) 
select dbo.UFN_SubIndex('abcd,1234,ABCD,5678', ',', 3)