我在下面有这个功能我正在打破一个字符串,例如 string =' 100001 | 125000,50001 - 75000'下面的结果表有一个更简单的方法吗?
low high
100001 125000
50001 75000
ALTER FUNCTION [dbo].[GetRange] (@String varchar(max))
returns @temptable TABLE (low int, high int)
as
begin
declare @separated table(items varchar(max))
insert into @separated select * from dbo.Split(@String, '|')
update @separated
set items = items + ',2147483647'
where charindex(',', items) = 0
insert into @temptable
select left(items, charindex(',', items) - 1)
, right(items, len(items) - charindex(',', items))
from @separated
return
end
答案 0 :(得分:2)
嗯......您可以删除拆分功能并将其替换为UNION
,并且可能更快。这将消除您的功能和嵌套功能。我想这取决于你的用例。它至少会移除您的dbo.Split
功能,该功能希望基于注意事项from this article.,但如果不是,则可能会非常慢。
declare @table table (a varchar(4000))
insert into @table (a) values
('100001|125000,50001 - 75000'),
('101321320001|1250132100,52130001 - 755000')
select
left(left(a,charindex(',',a) - 1),charindex('|',left(a,charindex(',',a) - 1)) - 1) as Low
,right(left(a,charindex(',',a) - 1),len(left(a,charindex(',',a) - 1)) - charindex('|',left(a,charindex(',',a) - 1))) as High
from @table
union all
select
left(right(a,len(a) - charindex(',',a)),CHARINDEX('-',right(a,len(a) - charindex(',',a))) - 1)
,right(right(a,len(a) - charindex(',',a)),len(right(a,len(a) - charindex(',',a))) - charindex('-',right(a,len(a) - charindex(',',a))))
from @table
答案 1 :(得分:2)
注意:这是假设分隔符是逗号并且范围可以用|分割或破折号。您可能会注意到破折号被替换为|为了一致性。
CREATE FUNCTION [dbo].[TestFunction] (@String varchar(max))
Returns Table
As
Return (
Select Low = try_convert(int,Left(RetVal,charindex('|',RetVal)-1))
,High = try_convert(int,Right(RetVal,charindex('|',reverse(RetVal))-1))
From (
Select RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(500)')))
From (Select x = Cast('<x>' + replace((Select replace(replace(@String,'-','|'),',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
Cross Apply x.nodes('x') AS B(i)
) B
)
Select * from [dbo].[TestFunction]('100001|125000,50001 - 75000')
返回
Low High
100001 125000
50001 75000