Wenn Sie auf SQL sind Server 2016 können Sie die eingebaute string_split
Funktion verwenden.
Wenn nicht, benötigen Sie Ihre eigene Funktion. Eine, die sehr gut funktioniert, ist Jeff Modens tally table method. Meine veränderte Version dieser sieht wie folgt aus, so dass für den Benutzer angegebenen Trennzeichen und bei Bedarf bestimmte Werte:
create function dbo.StringSplit
(
@str nvarchar(4000) = ' ' -- String to split.
,@delimiter as nvarchar(1) = ',' -- Delimiting value to split on.
,@num as int = null -- Which value to return.
)
returns table
as
return
(
-- Start tally table with 10 rows.
with n(n) as (select n from (values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n(n))
-- Select the same number of rows as characters in isnull(@str,'') as incremental row numbers.
-- Cross joins increase exponentially to a max possible 10,000 rows to cover largest isnull(@str,'') length.
,t(t) as (select top (select len(isnull(@str,'')) a) row_number() over (order by (select null)) from n n1,n n2,n n3,n n4)
-- Return the position of every value that follows the specified delimiter.
,s(s) as (select 1 union all select t+1 from t where substring(isnull(@str,''),t,1) = @delimiter)
-- Return the start and length of every value, to use in the SUBSTRING function.
-- ISNULL/NULLIF combo handles the last value where there is no delimiter at the end of the string.
,l(s,l) as (select s,isnull(nullif(charindex(@delimiter,isnull(@str,''),s),0)-s,4000) from s)
select rn as ItemNumber
,Item
from(select row_number() over(order by s) as rn
,substring(isnull(@str,''),s,l) as item
from l
) a
where rn = @num -- Return a specific value where specified,
or @num is null -- Or everything where not.
)
go
und wird wie folgt verwendet:
declare @t table (ID int, MULTI_CODES nvarchar(50));
insert into @t values (1,'10-101-102'),(2,'20-201-202'),(3,'30-301-302');
select t.ID
,t.MULTI_CODES
,s.Item as SINGLE_CODE
,s.ItemNumber as [Level]
from @t t
outer apply dbo.StringSplit(t.MULTI_CODES,'-',null) s
order by t.ID
,s.ItemNumber;
Welche Ausgänge:
+----+-------------+-------------+-------+
| ID | MULTI_CODES | SINGLE_CODE | Level |
+----+-------------+-------------+-------+
| 1 | 10-101-102 | 10 | 1 |
| 1 | 10-101-102 | 101 | 2 |
| 1 | 10-101-102 | 102 | 3 |
| 2 | 20-201-202 | 20 | 1 |
| 2 | 20-201-202 | 201 | 2 |
| 2 | 20-201-202 | 202 | 3 |
| 3 | 30-301-302 | 30 | 1 |
| 3 | 30-301-302 | 301 | 2 |
| 3 | 30-301-302 | 302 | 3 |
+----+-------------+-------------+-------+
Ich schlage vor, uns zu zeigen, was Sie versucht haben. Werfen Sie auch einen Blick auf [how to ask] (https://stackoverflow.com/help/how-to-ask), um eine qualitativ hochwertige Frage zu stellen, die höhere Chancen auf eine schnelle und genaue Antwort bietet. Vielen Dank. –
String Split und Pivot? –
welche Version von SQL Server? –