【问题标题】:Substring after a dot in SQL ServerSQL Server 中点后的子字符串
【发布时间】:2020-04-30 03:12:38
【问题描述】:

我有一个字段包含这样的数据

Product.Company.Price.Item

我想在最后一个点之后对任何字符串进行子串化。所以它看起来像这样

Item

我知道 MySQL 中有一个 substring.index 函数。如何在 SQL Server 中实现这一点?

【问题讨论】:

  • 如果总是不超过 4 个组件并且它们碰巧满足与标识符相同的限制,那么 PARSENAME('Product.Company.Price.Item',1)

标签: sql sql-server substring


【解决方案1】:
select  reverse(substring(reverse(fieldName),1,charindex('.',reverse(fieldname))-1))

这会做你想做的事,但我不会将它用作 where 表达式的一部分

declare @x varchar(50) = 'Product.Company.Price.Item'
select  substring(@x,len(@x)-charindex('.',reverse(@x))+2,99)

【讨论】:

  • 应该不需要三个 REVERSE。应该只需要一个找出最后一个点相对于字符串末尾的索引。然后你可以用 RIGHT
【解决方案2】:

希望此查询适用于您的案例:

DECLARE @VAR VARCHAR(MAX)='Product.Company.Price.Item'

SELECT RIGHT(@VAR, CHARINDEX('.', REVERSE(@VAR) + '.') - 1) AS VARL

【讨论】:

    【解决方案3】:

    如果总是 4 个部分,那么您可以使用 parsename() as

    select parsename('Product.Company.Price.Item', 1)
    

    或者使用right()charindex()作为

    select right(str, p)
    from
    (
        values ('Product.Company.Price.Item'), ('Other.row')
    ) t(str) cross apply
    (
        values (charindex('.', reverse(str))-1)
    ) tt(p)
    

    【讨论】:

      【解决方案4】:

      您可以使用Reverse()Left()CHARINDEX() 等函数进行尝试。

      DECLARE @Sentence VARCHAR(100) = 'Product.Company.Price.Item';
      
      SELECT REVERSE(LEFT(REVERSE(@Sentence),
      CHARINDEX('.',REVERSE(@Sentence))- 1)) AS [Last_Word]
      

      【讨论】:

        猜你喜欢
        • 2014-03-21
        • 2014-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-17
        • 1970-01-01
        • 2017-01-12
        • 2016-05-28
        相关资源
        最近更新 更多