-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyListGetAt-v3.sql
100 lines (80 loc) · 1.84 KB
/
MyListGetAt-v3.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
-- =============================================
-- Author: <soncu>
-- Create date: <24.06.2013>
-- Description: <T-Sql version of ListGetAt that supports
-- negative position for backward index and multiple delimiters
-- at once also empty element is optional with an argument>
-- =============================================
CREATE FUNCTION [dbo].[MyListGetAt]
(
@string varchar(1000),
@position int,
@delimiters varchar(50) = ',',
@ignoreEmptySpaces bit = 1
)
RETURNS varchar(1000)
AS
BEGIN
declare @str varchar(1000);
declare @sub varchar(1000);
declare @del varchar(1000);
declare @ignoreEmpty bit;
declare @reverseOrd bit;
declare @count int;
declare @start int;
declare @end int;
declare @len int;
declare @retPos int;
set @str = @string;
set @sub = '';
set @del = @delimiters;
set @ignoreEmpty = @ignoreEmptySpaces;
set @reverseOrd = (case when @position < 0 then 1 else 0 end);
set @count = 1;
set @start = 1;
set @retPos = ABS(@position);
if @reverseOrd = 1
begin
set @str = REVERSE(@str);
end
if DATALENGTH(@del) > 1
begin
declare @d varchar(1);
declare @i int;
set @d = left(@del, 1);
set @i = 2;
while @i <= DATALENGTH(@del)
begin
set @str = REPLACE(@str, SUBSTRING(@del, @i, 1), @d);
set @i = @i + 1;
end
set @del = @d;
end
while @start <= DATALENGTH(@str) + 1
begin
set @end = CHARINDEX(@del, @str, @start);
if @end = 0
begin
set @end = DATALENGTH(@str) + 1;
end
set @len = @end - @start;
if @ignoreEmpty = 1 and @len = 0
begin
set @start = @start + 1;
continue;
end
if @count = @retPos
begin
break;
end
set @start = @end + 1;
set @count = @count + 1;
end
if @start > DATALENGTH(@str) + 1
begin
RETURN '';
end
set @sub = SUBSTRING(@str, @start, @len);
RETURN (case when @reverseOrd = 1 then REVERSE(@sub) else @sub end);
END
GO