MS SQL: funzione per lo split di una stringa
Ecco una comoda funzione che trasforma una stringa in una tabella, 'splittandola' utilizzando un delimitatore:
[sourcecode lang="sql"]
CREATE function [dbo].[Split] (
@string nvarchar(4000),
@delimiter nvarchar(10)
) returns @table table (
[Value] nvarchar(4000)
)
begin
declare @nextString nvarchar(4000)
declare @pos int, @nextPos int
declare @commaCheck nvarchar(1)
set @nextString = ''
set @commaCheck = right(@string, 1)
set @string = @string + @delimiter
set @pos = charindex(@delimiter, @string)
set @nextPos = 1
while (@pos <> 0)
begin
set @nextString = substring(@string, 1, @pos - 1)
insert into @table ([Value]) values (@nextString)
set @string = substring(@string, @pos + 1, len(@string))
set @nextPos = @pos
set @pos = charindex(@delimiter, @string)
end
return
[/sourcecode]
[sourcecode lang="sql"]
CREATE function [dbo].[Split] (
@string nvarchar(4000),
@delimiter nvarchar(10)
) returns @table table (
[Value] nvarchar(4000)
)
begin
declare @nextString nvarchar(4000)
declare @pos int, @nextPos int
declare @commaCheck nvarchar(1)
set @nextString = ''
set @commaCheck = right(@string, 1)
set @string = @string + @delimiter
set @pos = charindex(@delimiter, @string)
set @nextPos = 1
while (@pos <> 0)
begin
set @nextString = substring(@string, 1, @pos - 1)
insert into @table ([Value]) values (@nextString)
set @string = substring(@string, @pos + 1, len(@string))
set @nextPos = @pos
set @pos = charindex(@delimiter, @string)
end
return
[/sourcecode]