由于已经提出了一个建议,并且在字符串中隔离数字的建议使用了 while 循环,因此我需要发布一个不使用任何循环的替代方案。相反,它使用计数或数字表。有很多解决方案。我喜欢使用速度快且读取次数为零的视图。
这是我的计数表版本。
create View [dbo].[cteTally] as
WITH
E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)
select N from cteTally
接下来我们需要一个表值函数来使用我们的计数表删除不是数字的字符。这也非常快,因为我们使用的是计数表而不是循环。
create function GetOnlyNumbers
(
@SearchVal varchar(8000)
) returns table as return
with MyValues as
(
select substring(@SearchVal, N, 1) as number
, t.N
from cteTally t
where N <= len(@SearchVal)
and substring(@SearchVal, N, 1) like '[0-9]'
)
select distinct NumValue = STUFF((select number + ''
from MyValues mv2
order by mv2.N
for xml path('')), 1, 0, '')
from MyValues mv
现在我们已经完成了所有的跑腿工作,我们可以专注于手头的任务。由于您没有提供任何示例数据,我只是编造了一些东西。我不确定这是否代表您的数据,但这适用于我创建的示例数据。
if OBJECT_ID('tempdb..#Something') is not null
drop table #Something
create table #Something(SomeVal varchar(100))
insert #Something values
('Maybe you have other stuff in here. 5552223333 additional characters can cause grief')
, ('321-654-9878')
, ('123)-333-4444')
, ('1234567')
select replace(format(try_convert(bigint, n.NumValue), '(###) ###-####'), '() ', '')
, n.NumValue
from #Something s
cross apply dbo.GetOnlyNumbers(s.SomeVal) n
格式化数据的输出如下所示:
(555) 222-3333
(321) 654-9878
(123) 333-4444
123-4567