/ Published in: SQL
From StackOverflow. I'm still not quite happy with my understanding of it, but it looks an order of magnitude more elegant than most I've found.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
CREATE FUNCTION dbo.Split (@sep CHAR(1), @s VARCHAR(512)) RETURNS TABLE AS RETURN ( WITH Pieces(pn, START, stop) AS ( SELECT 1, 1, CHARINDEX(@sep, @s) UNION ALL SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1) FROM Pieces WHERE stop > 0 ) SELECT pn, SUBSTRING(@s, START, CASE WHEN stop > 0 THEN stop-START ELSE 512 END) AS s FROM Pieces ) --Here's a simpler demo of the CTE Recursion with the string parsing removed for clarity: --Part before the UNION is called the Anchor expression. BEGIN WITH Pieces(START, stop) AS ( SELECT 2, 2 UNION ALL SELECT START + 1, stop + 1 FROM Pieces WHERE stop < 5 ) SELECT START, stop FROM Pieces END --Returns --start stop --2 2 --3 3 --4 4 --5 5