Advertisement
infogulch

Untitled

Aug 31st, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.58 KB | None | 0 0
  1. -- splits a string by a delimiter string and returns each part in a table with a 1-based index in order of occurrence.
  2. -- it should be deterministic, no?
  3.  
  4. CREATE FUNCTION dbo.ufn_Split( @str nvarchar(max), @d varchar(5) )
  5. RETURNS @List TABLE (id int PRIMARY KEY, item nvarchar(max))
  6. AS
  7. BEGIN
  8.     DECLARE @pos int = 1, @lpos int = 1, @id int = 0
  9.     WHILE LEN(@str) >= @pos BEGIN
  10.         SET @id = @id+1; SET @pos = CHARINDEX(@d,@str,@lpos);
  11.         IF @pos = 0 SET @pos = LEN(@str)+1;
  12.         INSERT INTO @List SELECT @id AS id, SUBSTRING(@str,@lpos,@pos-@lpos);
  13.         SET @lpos = @pos+1;
  14.     END
  15.     RETURN
  16. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement