第一分割的逗號分隔的值,則得到使用遞歸公用表表達式的值。
Declare @values nvarchar(max) = '1000-1050, 1054, 1090-1230, 1245'
;with ranges_cte as
(
select cast(case pos when 0 then ResultValue else left(ResultValue,pos-1) end as int) first, cast(case pos when 0 then ResultValue else substring(ResultValue,pos+1,len(ResultValue)-pos) end as int) Last
from (
select ResultValue, charINDEx('-',ResultValue) pos
from dbo.SplitString(@values,',')) x
)
, values_rte as
(
select first,last,first as active
from ranges_cte
union all
select first,last,active +1 as active
from values_rte
where active< last
)
select *
from values_rte
OPTION (MAXRECURSION 0)
功能分裂值:
Create FUNCTION [dbo].[SplitString] (@StringArray NVARCHAR(MAX), @Delimiter NVARCHAR(10))
RETURNS @ResultedValues table
(
nr int,
ResultValue nvarchar(max)
)
AS
--select * from dbo.splitstring ('123,456,789',',')
BEGIN
declare @string nvarchar(max)
declare @nr int = 1
set @string = @StringArray
WHILE (CHARINDEX(@Delimiter,@String)>0)
BEGIN
INSERT INTO @ResultedValues (nr,ResultValue) VALUES (@nr,LTRIM(RTRIM(SUBSTRING(@String,1,CHARINDEX(@Delimiter,@String)-1))))
SET @String = SUBSTRING(@String, CHARINDEX(@Delimiter,@String)+LEN(@Delimiter),LEN(@String))
set @nr = @nr +1
END
INSERT INTO @ResultedValues (nr,ResultValue) VALUES (@nr, LTRIM(RTRIM(@String)))
RETURN
END