如何从 nvarchar 获取数字

发布于 2024-11-01 22:12:27 字数 438 浏览 0 评论 0原文

我有一个名为 Foo 的表,还有一个名为 Bar 的列,它是一个 nvarchar

Bar 的值如下所示: Prefix + Number

示例:

Bar = 'abc123'
Bar = 'a1bc23'

我想选择 Bar 的 Number 部分(后半部分),这将是:

123 if Bar = 'abc123'
23 if Bar = 'a1bc23'

假设前缀没有结束带有数字,如何获得 Bar 的数字部分?

注意:

  • 我们不知道前缀的长度
  • T-SQL 或 LINQ 解决方案都可以。

预先感谢您抽出时间。

I have a table called Foo and there is a column named Bar, which is an nvarchar.

The values of Bar look like this: Prefix + Number

Examples:

Bar = 'abc123'
Bar = 'a1bc23'

I would like to select the Number part (second half) of Bar, which would be:

123 if Bar = 'abc123'
23 if Bar = 'a1bc23'

Presuming that the prefix doesn't end with a number how can I get the number part of Bar?

NOTES:

  • We don't know the length of the prefix
  • Either a T-SQL or a LINQ solution would be fine.

Thank you in advance for your time.

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

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

发布评论

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

评论(2

君勿笑 2024-11-08 22:12:27
WITH T(C)
AS
(
SELECT 'a1bc23' UNION ALL 
SELECT 'abc123' UNION ALL 
SELECT 'FOO'    UNION ALL 
SELECT  NULL    UNION ALL 
SELECT '456' 
)
SELECT 
      CASE WHEN C LIKE '%[0-9]' 
           THEN CASE WHEN C LIKE '%[^0-9]%' 
                     THEN RIGHT(C,PATINDEX('%[^0-9]%', REVERSE(C))-1) 
                     ELSE C
                 END
      END AS Number
FROM T 

退货

Number
------
23
123
NULL
NULL
456
WITH T(C)
AS
(
SELECT 'a1bc23' UNION ALL 
SELECT 'abc123' UNION ALL 
SELECT 'FOO'    UNION ALL 
SELECT  NULL    UNION ALL 
SELECT '456' 
)
SELECT 
      CASE WHEN C LIKE '%[0-9]' 
           THEN CASE WHEN C LIKE '%[^0-9]%' 
                     THEN RIGHT(C,PATINDEX('%[^0-9]%', REVERSE(C))-1) 
                     ELSE C
                 END
      END AS Number
FROM T 

Returns

Number
------
23
123
NULL
NULL
456
番薯 2024-11-08 22:12:27

马丁对于如何做到这一点有一个很好的答案。虽然我确信这会起作用,但它可能会是一个昂贵的调用,因为您正在字符串字段上执行几个操作。如果您有数千或数百万行,则这可能性能不佳。

我可能建议查看为什么需要这样做,并看看是否可以以更容易处理这种情况的方式格式化数据。将一个字段拆分为 2 个字段,并具有前缀字段和后缀字段或类似的内容。特别是如果这些是“智能零件号”或类似的东西,您将能够更轻松地按语法进行分组。

Martin has a good answer for how to do it. While I'm sure this would work, it could turn out to be an expensive call, since you're doing a couple operations on a string field. If you have 1000s or millions of rows, this might not be performant.

I might suggest looking at the why you need to do this, and see if you can format your data in a way that would make it easier to handle this situation. Split the one field into 2 and have a prefix field and suffix field or something along those lines. Especially if these are "smart part numbers" or something along those lines, you would be able to do group by syntax easier.

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