1. 程式人生 > >SQL根據下標,返回split分割後字串

SQL根據下標,返回split分割後字串

-- =============================================
-- Author:        
-- Create date: 
-- Description:   根據下標(0開始),返回split分割後字串,越界返回空字串
-- eg:SELECT dbo.Split_GetByIndex('w1,w2,,,,w,w,ew',',',1)
-- =============================================CREATE FUNCTION [dbo].[Split_GetByIndex]
(
    @SplitStr  NVARCHAR
(max), @SplitChar NVARCHAR(10), @Index INT ) RETURNS nvarchar(50) AS BEGIN DECLARE @i INT DECLARE @result NVARCHAR(100) SET @result='' SET @SplitStr=LTRIM(RTRIM(@SplitStr)) SET @i=0 WHILE CHARINDEX(@SplitChar,@SplitStr)>0 BEGIN IF @i=@Index BEGIN
SET @result=LEFT(@SplitStr,CHARINDEX(@SplitChar,@SplitStr)-1) BREAK END SET @i=@i+1 SET @SplitStr=RIGHT(@SplitStr,LEN(@SplitStr)-CHARINDEX(@SplitChar,@SplitStr)) END IF CHARINDEX(@SplitChar,@SplitStr)=0 AND @i=@Index BEGIN SET
@result=@SplitStr END RETURN @result END