forked from ktaranov/sqlserver-kit
-
Notifications
You must be signed in to change notification settings - Fork 14
/
udf_strtok.sql
101 lines (87 loc) · 2.66 KB
/
udf_strtok.sql
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
CREATE Function udf_strtok (
@sStringToParse Varchar(max)
,@sSeparator char(1)
,@nStartPosition int
)
Returns @tbResult Table (
Token Varchar(max)
,NextStartPosition int
)
AS
Begin
Declare
@nNextPos int
,@nLenStringToParse int
,@sToken varchar(max)
Select @nLenStringToParse = Len(@sStringToParse)
-- Special case: input string is null
If @sStringToParse Is Null
Begin
Select
@nNextPos = Null
,@sToken = Null
End
-- Special case: separador is null. Return full input string
Else If @sSeparator Is Null
Begin
Select
@nNextPos = @nLenStringToParse + 1
,@sToken = Substring(@sStringToParse, @nStartPosition, @nLenStringToParse)
End
-- Special case: input string is empty.
Else If @nLenStringToParse = 0
Begin
If @nStartPosition = 1
Select
@nNextPos = 2
,@sToken = @sStringToParse
Else
Select
@nNextPos = @nStartPosition + 1
,@sToken = Null
End
-- Special case: input string ends with separator
Else If @nStartPosition = @nLenStringToParse + 1
And Substring(@sStringToParse, @nLenStringToParse, 1) = @sSeparator
Begin
Select
@nNextPos = @nStartPosition + 1
,@sToken = ''
End
-- In any other case if we are at the end of the input string, return null signalling end...
Else If @nStartPosition > @nLenStringToParse
Begin
Select
@nStartPosition = Null
,@sToken = Null
End
-- Normal cases...
Else
Begin
Select @nNextPos = CharIndex(@sSeparator, @sStringToParse, @nStartPosition)
If @nNextPos Is Null
Begin
Select
@sToken = Null
,@nNextPos = Null
End
-- Separator not found: return the full string
Else If @nNextPos = 0
Begin
If @nStartPosition = 0
Select @sToken = @sStringToParse
Else
Select @sToken = SUBSTRING( @sStringToParse, @nStartPosition, @nLenStringToParse )
Select @nNextPos = @nLenStringToParse + 1
End
Else
Begin
Select @sToken = SUBSTRING( @sStringToParse, @nStartPosition, @nNextPos - @nStartPosition )
Select @nNextPos = @nNextPos + 1
End
Set @nStartPosition = @nNextPos
End
Insert Into @tbResult (NextStartPosition, Token)
Values (@nNextPos, @sToken)
Return
End