SQL Split Function

  1. CREATE FUNCTION [dbo].[SplitString]  
  2. (     
  3.     @DelimitedString    varchar(8000),  
  4.     @Delimiter              varchar(100)   
  5.     )  
  6. RETURNS @tblArray TABLE  
  7.     (  
  8.     Element     varchar(1000)               -- Array element contents  
  9.     )  
  10. AS  
  11. BEGIN  
  12.   
  13.     -- Local Variable Declarations  
  14.     -- ---------------------------  
  15.     DECLARE @Index      smallint,  
  16.                     @Start      smallint,  
  17.                     @DelSize    smallint  
  18.   
  19.     SET @DelSize = LEN(@Delimiter)  
  20.   
  21.     -- Loop through source string and add elements to destination table array  
  22.     -- ----------------------------------------------------------------------  
  23.     WHILE LEN(@DelimitedString) > 0  
  24.     BEGIN  
  25.   
  26.         SET @Index = CHARINDEX(@Delimiter, @DelimitedString)  
  27.   
  28.         IF @Index = 0  
  29.             BEGIN  
  30.   
  31.                 INSERT INTO  
  32.                     @tblArray   
  33.                     (Element)  
  34.                 VALUES  
  35.                     (LTRIM(RTRIM(@DelimitedString)))  
  36.   
  37.                 BREAK  
  38.             END  
  39.         ELSE  
  40.             BEGIN  
  41.   
  42.                 INSERT INTO  
  43.                     @tblArray   
  44.                     (Element)  
  45.                 VALUES  
  46.                     (LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))  
  47.   
  48.                 SET @Start = @Index + @DelSize  
  49.                 SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)  
  50.   
  51.             END  
  52.     END  
  53.   
  54.     RETURN  
  55. END  
  56.   
  57. GO  
  58.   
  59. SELECT * FROM dbo.SplitString ('10:50'':')  
Output:
 
Element
10
50