forked from smpetersgithub/AdvancedSQLPuzzles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString Split Recursion.sql
More file actions
53 lines (48 loc) · 1.42 KB
/
Copy pathString Split Recursion.sql
File metadata and controls
53 lines (48 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*----------------------------------------------------
Scott Peters
String Split
https://advancedsqlpuzzles.com
Last Updated: 01/13/2023
Microsoft SQL Server T-SQL
This script uses recursion to split a string into rows of substrings, based on a specified separator character
This script provides the same functionality of the STRING_SPLIT function.
*/----------------------------------------------------
-------------------------------
-------------------------------
DROP TABLE IF EXISTS #Example;
GO
-------------------------------
-------------------------------
SELECT *
INTO #Example
FROM (VALUES(1,'George Washington'),(2,'Thomas Jefferson')) n(Id,String);
GO
-------------------------------
-------------------------------
;WITH cte_String AS
(
SELECT Id,
CAST(String AS VARCHAR(200)) AS String
FROM #Example
),
cte_Recursion AS
(
SELECT Id,
String,
1 AS Starts,
CHARINDEX(' ', String) AS Position
FROM cte_String
UNION ALL
SELECT Id,
String,
Position + 1,
CHARINDEX(' ', String, Position + 1)
FROM cte_Recursion
WHERE Position > 0
)
SELECT ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Starts) AS RowNumber,
*,
SUBSTRING(String, Starts, CASE WHEN Position > 0 THEN Position - Starts ELSE LEN(String) END) Word,
LEN(String) - LEN(REPLACE(String,' ','')) AS TotalSpaces
FROM cte_Recursion
ORDER BY Id, Starts;