【问题标题】:Substing - Get date from inbetween characters子字符串 - 从字符之间获取日期
【发布时间】:2021-03-31 08:24:14
【问题描述】:

我有一个可变大小的varchar 列。该列中的值可能不同,例如

###LoggedIn 2021-03-30 16:09:10###
I have ###LoggedIn 2021-03-29 16:09:10### regularly
I am not sure if I ###LoggedIn 2021-03-28 16:09:10### 

我只想从字符串中获取日期。 我试过Substring,但它只适用于第一个场景。我想要一个适用于所有场景的脚本。不只是这 3 个,还有更多。

select CAST(ISNULL(SUBSTRING('###LoggedIN 2021-03-04 16:09:10###', 13, 11),'1900-01-01')  AS date)

【问题讨论】:

  • 你过得怎么样?

标签: sql sql-server tsql substring


【解决方案1】:

使用patindex 查找字符串的已知部分。然后使用substring 拉出日期。

select
    x.col1
    -- Find the end of the date and substring it. Convert to date.
    , convert(date, substring(y.col2, 1, patindex('%###%', y.col2)-1))
from (
    values
    ('###LoggedIn 2021-03-30 16:09:10###')
    , ('I have ###LoggedIn 2021-03-29 16:09:10### regularly')
    , ('I am not sure if I ###LoggedIn 2021-03-28 16:09:10###')
) x (Col1)
-- Find the start of the date, and substring it, use cross apply so we can use this multiple times
cross apply (values (substring(x.col1, patindex('%###LoggedIn %', x.col1)+12, len(x.col1)))) y (col2);

【讨论】:

    【解决方案2】:

    您提供的数据遵循非常规律的模式。大概,您想要'###LoggedIn ' 之后的日期。这意味着你可以只寻找那个模式,走到最后,然后取 19 个字符:

    select v.*,
           substring(col, charindex('###LoggedIn ', col) + 12, 19)
    from (values ('###LoggedIn 2021-03-30 16:09:10###'),
                 ('I have ###LoggedIn 2021-03-29 16:09:10### regularly'),
                 ('I am not sure if I ###LoggedIn 2021-03-28 16:09:10###')
         ) v (col);
    

    【讨论】:

      【解决方案3】:

      您可以在patindex 中使用子字符串

      select convert(date,substring('###LoggedIN 2021-03-04 16:09:10###',patindex('%###LoggedIn %','###LoggedIN 2021-03-04 16:09:10###')+12,10)) 
      

      从表

       select convert(date,substring(Column,patindex('%###LoggedIn %',Column)+12,10)) from YourTable
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多