如何使用patindex和substring解析特定值的字符串?

发布于 2025-02-08 19:45:00 字数 537 浏览 1 评论 0原文

我有以下示例:

declare @test1 varchar(max) = 'Month 05/2022, Ord195506 Cst373175'
declare @test2 varchar(max) = 'Month 05/2022, Ord195506 Cst373175, something...'

select SUBSTRING(@test, PATINDEX('%Ord[0-9][0-9][0-9][0-9][0-9][0-9]%', @test1) + 3, 6)

我需要获取以下值:

  • 05/2022
  • 195506
  • 373175

必须注意,ord> ord> ordabo的数字未固定为长度6。它们可以从1到任何数字。

是否可以将字符串分为必要的值,而无需大量patindexsubstring

I have the following example:

declare @test1 varchar(max) = 'Month 05/2022, Ord195506 Cst373175'
declare @test2 varchar(max) = 'Month 05/2022, Ord195506 Cst373175, something...'

select SUBSTRING(@test, PATINDEX('%Ord[0-9][0-9][0-9][0-9][0-9][0-9]%', @test1) + 3, 6)

I need to get the following values:

  • 05/2022
  • 195506
  • 373175

It must be noted that the numbers behind Ord and Abo are not fixed to a length of 6. They can be from 1 to any number.

Is it even possible to split the string into required values without a multitude of PATINDEX, SUBSTRING and RIGHT?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘香 2025-02-15 19:45:00

对于您的问题中的示例,您可以 string_split 在空间上的字符串中的元素,然后使用 translate 删除非数字元素,例如:

declare @test1 varchar(max) = 'Month 05/2022, Ord195506 Cst373175'

select result
from (select @test1)t(test)
cross apply(
  select Trim(Translate([value],'abcdefghijklmnopqrstuvwxyz,',Space(27))) result
    from String_Split(test, ' ')
)s
where result !='';

For the example in your question you could string_split the elements in the string on the space and then remove the non-numeric elements using translate, such as:

declare @test1 varchar(max) = 'Month 05/2022, Ord195506 Cst373175'

select result
from (select @test1)t(test)
cross apply(
  select Trim(Translate([value],'abcdefghijklmnopqrstuvwxyz,',Space(27))) result
    from String_Split(test, ' ')
)s
where result !='';

Example DB<>Fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文