--Description: Splitting a string function--SELECT * FROM dbo. Split (' a,b,c,d,e,f,g ', ', ')-- =============================================CREATE FUNCTION [dbo].[Split](@Text VARCHAR(8000) ,@Sign NVARCHAR(4000) ) RETURNS @tempTable TABLE(IDINT IDENTITY(1,1)PRIMARY KEY,[TempVal] VARCHAR(4000) ) as BEGIN DECLARE @StartIndex INT --where to start looking DECLARE @FindIndex INT --location found DECLARE @Content VARCHAR(4000)--the value foundSET @StartIndex = 1 --The find position of a string in T-SQL starts at 1SET @FindIndex = 0 --start loop lookup string comma while(@StartIndex <= LEN(@Text))BEGIN --The return value is where the string was foundSELECT @FindIndex = CHARINDEX(@Sign,@Text,@StartIndex)--Judging if there's no found. return 0 IF(@FindIndex = 0 OR @FindIndex is NULL)BEGIN --if we don't find them , we're done.SET @FindIndex = LEN(@Text)+ 1 END --Initialize the location of the next lookupSET @Content = LTRIM(RTRIM(SUBSTRING(@Text,@StartIndex,@FindIndex - @StartIndex)))SET @StartIndex = @FindIndex + 1 --Insert the value you are looking for in the table type that you want to returnINSERT into @tempTable([TempVal])VALUES(@Content)END RETURN END
SQL Server Split String functions