-
Notifications
You must be signed in to change notification settings - Fork 2
/
sqlserver2022-tsql-string_split.sql
103 lines (49 loc) · 1.88 KB
/
sqlserver2022-tsql-string_split.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
102
103
/*
SQL Server 2022
- funkcja STRING_SPLIT
https://www.kursysql.pl
*/
USE AdventureWorks2019
SELECT value FROM STRING_SPLIT('Lorem ipsum dolor sit amet.', ' ')
-- min 130 compat level
ALTER DATABASE AdventureWorks2019 SET COMPATIBILITY_LEVEL = 120
GO
-- ! 208 Invalid object name 'STRING_SPLIT'.
SELECT value FROM STRING_SPLIT('Lorem ipsum dolor sit amet.', ' ')
ALTER DATABASE AdventureWorks2019 SET COMPATIBILITY_LEVEL = 130
GO
SELECT * FROM STRING_SPLIT('Chisel Epic Epic EVO Epic FSR Epic Hardtail Riprock', ' ')
-- wartości oddzielone przecinkiem, włącznie z pustą wartością
DECLARE @tags NVARCHAR(400) = 'Chisel,Epic,Epic EVO,Epic FSR,,Epic Hardtail,Riprock'
SELECT value
FROM STRING_SPLIT(@tags, ',')
-- usunięcie pustych wartości
SELECT value
FROM STRING_SPLIT(@tags, ',')
WHERE RTRIM(value) <> ''
GO
/*
enable_ordinal
A value of 1 enables the ordinal column.
If enable_ordinal is omitted, NULL, or has a value of 0, the ordinal column is disabled.
*/
SELECT *
FROM STRING_SPLIT('Chisel Epic Epic EVO Epic FSR Epic Hardtail Riprock', ' ')
SELECT *
FROM STRING_SPLIT('Chisel Epic Epic EVO Epic FSR Epic Hardtail Riprock', ' ', 1)
-- numerowane są też puste wartości
DECLARE @tags NVARCHAR(400) = 'Chisel,Epic,Epic EVO,Epic FSR,,Epic Hardtail,Riprock'
SELECT * FROM STRING_SPLIT(@tags, ',', 1)
-- wartość z kolumny ordinal, możemy od razy w zapytaniu, np. do filtrowania
SELECT *
FROM STRING_SPLIT('Chisel Epic Epic EVO Epic FSR Epic Hardtail Riprock', ' ', 1)
WHERE ordinal % 2 = 0
-- Typ danych varchar(max)
DECLARE @tags varchar(max) =
REPLICATE(CAST('Chisel,Epic,Epic EVO,Epic FSR,Epic Hardtail,Riprock,' AS varchar(max)), 2000)
SELECT @tags
SELECT LEN(@tags) AS tags_LEN
SELECT * FROM STRING_SPLIT(@tags, ',', 1)
ALTER DATABASE AdventureWorks2019 SET COMPATIBILITY_LEVEL = 160
GO