Monday, August 13, 2012

SQL string splitter


I really prefer to give credit for these types of things, but I don't remember where I found it :(

Basic syntax... select dbo.FN_STRING_HELPER_SPLIT('My name is James', ' ', 4) will return 'James'



CREATE FUNCTION [dbo].FN_STRING_HELPER_SPLIT
(
  @strToSplit as varchar(4000),
  @delimiter as varchar(50),
  @columnToReturn as int
)
RETURNS varchar(25)
AS
BEGIN
  -- Declartion of the return variable
  DECLARE @i as int
  DECLARE @occurrences as int
  DECLARE @delimiterIndex as int
  DECLARE @actSplitValue as varchar(4000)
 
  -- T-SQL statements to compute the return value here
  SET @i = 1
  SET @delimiterIndex = 1
 
  WHILE @i <= @columnToReturn
  BEGIN
    SET @delimiterIndex = CHARINDEX(@delimiter, @strToSplit)
    -- if not found end while
    SET @actSplitValue = @strToSplit
    IF @delimiterIndex = 0 BEGIN
      BREAK
    END
    SET @actSplitValue = LEFT(@strToSplit, @delimiterIndex - 1)
    -- SUBSTRING(string, von, bis)
    SET @strToSplit = SUBSTRING(@strToSplit ,@delimiterIndex +1, LEN(@strToSplit)- @delimiterIndex)
    SET @i = @i + 1
  END
  -- the result of the function
  RETURN @actSplitValue
END