字符串索引分割

USE [BIWORK_SSIS]
GO
/****** Object: UserDefinedFunction [dbo].[SplitStringByIndex] Script Date: 06/15/2015 12:52:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[SplitStringByIndex]
(
-- Add the parameters for the function here
@InputText nvarchar(max),
@Delimiter nchar = N' ',
@Index int
)
RETURNS nvarchar(255)
AS
BEGIN
-- Fill the table variable with the rows for your result set
declare @StartIndex int
declare @DelimiterIndex int
declare @Length int
declare @Slice nvarchar(255)
declare @TermIndex int
declare @val nvarchar(255)

set @StartIndex = 1
set @Length = DATALENGTH (@InputText)
set @TermIndex = 1

while @StartIndex <= @Length
begin
set @DelimiterIndex = charindex(@Delimiter, @InputText, @StartIndex)
if @DelimiterIndex = 0 -- If no separator found, treat entire string as a slice
set @DelimiterIndex = @Length + 1

set @Slice = rtrim(ltrim(substring(@InputText, @StartIndex, @DelimiterIndex - @StartIndex)))

if @Slice != N''
begin
if @TermIndex=@Index
begin
set @val=@Slice
break
end
set @TermIndex = @TermIndex + 1
end
set @StartIndex = @DelimiterIndex + 1
end
return @val
END

你可能感兴趣的:(字符串)