【问题标题】:SQL select decimal from String contain DateSQL 从包含日期的字符串中选择十进制
【发布时间】:2018-05-27 00:28:48
【问题描述】:

我只想要给定字符串中的数字十进制其他整数值

当前表输出:

        Column
        10.40  (10/14 after @ 10.3)  
        10.1%
        10%
        10/12/2017 10.45
        8.2  10/12
        15.20% 10/12/17
        11/12
        > 10.50
        < 50.10

预期输出:

        10.40
        10.1
        10
        10.45
        8.2
        15.20
        NULL
        NULL
        NULL

尝试查询:

        declare @strAlphaNumeric VARCHAR(max) ='completed 11/12 at Dr Lemons office'

         select 
        stuff(stuff( @strAlphaNumeric+'x',patindex('%[0-9][^0-9.]%', @strAlphaNumeric+'x') + 1, len( @strAlphaNumeric), '' ), 1, patindex('%[0-9]%',  @strAlphaNumeric) - 1,      
        '')         

有人可以帮忙吗?

【问题讨论】:

  • SQL 不是处理这类事情的最佳工具。

标签: sql substring sql-server-2016


【解决方案1】:

首先,正如 HoneyBadger 所建议的那样,SQL 不是正确的工具。但是,另一种方式

select case when TRY_CONVERT(money, LTRIM(SUBSTRING(Col1, PATINDEX('%[^0-9./]%', Col1), LEN(Col1)))) is null then
             cast(REPLACE(Col1,  LTRIM(SUBSTRING(Col1, PATINDEX('%[^0-9./]%', Col1), LEN(Col1)+1)), '') as varchar)
      else
             cast(TRY_CONVERT(money, LTRIM(SUBSTRING(Col1, PATINDEX('%[^0-9./]%', Col1), LEN(Col1)))) as varchar)  end [Col1] from <table>

结果:

Col1
10.40 
10.1
10
10.45
8.2  
15.20
BLANK
BLANK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 2022-01-21
    • 2014-10-07
    • 2015-12-19
    • 2023-04-08
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    相关资源
    最近更新 更多