【问题标题】:SQL String Removing Succeeding Characters from a specific characterSQL字符串从特定字符中删除后续字符
【发布时间】:2017-01-25 05:57:27
【问题描述】:

我的任务是显示类似于Foo - BarFoo-BarFoo - BarFoo!.,-BarFoo...-Bar 的字符串,我只需要将其显示为Foo。这意味着我必须删除 - 符号之后的所有字符以及它之前的所有特殊字符。我可以使用一个简单的函数来满足我提供给所需输出的所有字符串实例:Foo?我们使用 SQL Server 2008 r2。

编辑:我需要提一下,Foo 和 Bar 这两个词只是实际字符串的表示,因此对字符串长度进行硬编码是行不通的。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    我想出了这个(感谢 John Cappelletti 提供示例数据,自己解决您未来的问题):

    Declare @YourTable table (col varchar(50))
    Insert into @YourTable values
     ('Foo - Bar')
    ,('Foo-Bar')
    ,('Foo        - Bar')
    ,('Foo!.,-Bar')
    ,('Foo...-Bar')
    ,('aaa Foo - Bar aaa')
    

    查询:

    SELECT  col, 
            LEFT(BeforeDash, LEN(BeforeDash) - PATINDEX('%[a-z]%', REVERSE(BeforeDash))+1)
    FROM     
    (
        SELECT col, LEFT(col, CHARINDEX('-', col)) As BeforeDash
        FROM @YourTable
    ) derived
    

    结果:

    col                     Display
    Foo - Bar               Foo
    Foo-Bar                 Foo
    Foo        - Bar        Foo
    Foo!.,-Bar              Foo
    Foo...-Bar              Foo
    aaa Foo - Bar aaa       aaa Foo
    

    【讨论】:

      【解决方案2】:

      试试这个

         declare @String varchar(20)='Foo!.,-Bar'
         select substring(@String,charindex('F', @String),3)
      

      【讨论】:

      • 确实只有文本长度为3。
      • 等待它只适用于像 foo 这样的 3 个字母的单词,如果第一个单词是 3 或更多甚至 2 怎么办?喜欢foot?
      • @super-user 我的第二个答案将给出结果,如果字符串以 'foo' 开头,第一个答案将给出
      【解决方案3】:
      Declare @YourTable table (col varchar(50))
      Insert into @YourTable values
       ('Foo - Bar')
      ,('Foo-Bar')
      ,('Foo        - Bar')
      ,('Foo!.,-Bar')
      ,('Foo...-Bar')
      ,('aaa Foo-Bar aaa')
      ,('There is no Bar-Foo here')
      
      Declare @Search varchar(50) = 'Foo - Bar'
      Select *
            ,Display = case when col like '%'+Replace(@Search,' ','%')+'%' 
                            then Left(@Search,charindex('-',@Search)-1)
                            else col 
                       end
       From  @YourTable 
      

      返回

      col                         Display
      Foo - Bar                   Foo 
      Foo-Bar                     Foo 
      Foo        - Bar            Foo 
      Foo!.,-Bar                  Foo 
      Foo...-Bar                  Foo 
      aaa Foo-Bar aaa             Foo 
      There is no Bar-Foo here    There is no Bar-Foo here
      

      【讨论】:

        【解决方案4】:
           DECLARE @STRING VARCHAR(2000)
        SET @STRING = 'FOO - DEPTH'
        
        
        SELECT LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(@STRING, 0, CHARINDEX('-', @STRING)),'!',''),'.',''),',','')))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-22
          • 1970-01-01
          • 2017-04-25
          • 1970-01-01
          • 1970-01-01
          • 2022-10-12
          • 1970-01-01
          • 2015-10-02
          相关资源
          最近更新 更多