sql-server - 从字母数字字段中提取 6-8 位日期

标签 sql-server t-sql date ssis

截图说明了一切。 http://i46.tinypic.com/f3hobl.png

在当前配置下,InvoiceSentDate 仅接受 8 位数日期 (MM-DD-YY)。我也希望能够捕获 MM-DD-YYYY 日期。我该怎么做?

为了进行比较,请查看发票 2106-2112 与 2116。

此外,让事情变得复杂!有些记录在日期后有文本。 http://i50.tinypic.com/2r5qa88.png

最佳答案

您可以使用纯 T-SQL 来完成此操作。这是工作SqlFiddle .

在这里,我使用 patindex 查找日期,然后查找其后的第一个非数字。这给出了 substring 单独提取日期所需的参数。正如您所看到的,我添加了一些测试数据,涵盖了各种可能性,包括斜线和破折号日期分隔符。

-- Test data
declare @Demo table (
    RawData varchar(100) null
)
insert into @Demo select 'JS sent via Unifier on 08/29/2012'
insert into @Demo select 'i sent via email on 09/07/12'
insert into @Demo select 'i sent via Unifier on 01/04/12; resubmitting p...'
insert into @Demo select 'JS sent via Unifier on 08-29-2012; resubmitting p...'
insert into @Demo select '08-29-2012; resubmitting p...'
insert into @Demo select '08-29-12'
insert into @Demo select 'no date here'
insert into @Demo select null

-- Actual query
select *,
    -- If there's a date, display it
    case when StartChar > 0 then substring(RawData, StartChar, DateLen) else null end as DateString 
from (
    select *,
        -- Find the first date
        patindex('%[0-1][0-9][/-][0-3][0-9][/-][0-9][0-9]%', RawData) as StartChar,
        -- Find the first non-digit after that date
        patindex(
            '%[^0-9]%', 
            right(
                RawData + '_', -- This underscore adds at least one non-digit to find
                len(RawData) - patindex('%[0-1][0-9][/-][0-3][0-9][/-][0-9][0-9]%', RawData) - 6
            )
        ) + 7 as DateLen
    from @Demo
) as a

更新

如果您只是寻找 2 种可能的日期格式,则只需检查它们即可使查询变得更简单:

select *,
    -- If there's a date, display it
    case
        when StartChar1 > 0 then substring(RawData, StartChar1, 10)
        when StartChar2 > 0 then substring(RawData, StartChar2, 8)
        else null
    end as DateString 
from (
    select *,
        -- Find the first MM-DD-YYYY
        patindex('%[0-1][0-9][/-][0-3][0-9][/-][0-9][0-9][0-9][0-9]%', RawData) as StartChar1,
        -- Find the first MM-DD-YY
        patindex('%[0-1][0-9][/-][0-3][0-9][/-][0-9][0-9]%', RawData) as StartChar2
    from @Demo
) as a

关于sql-server - 从字母数字字段中提取 6-8 位日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12532839/

相关文章:

java:有纪元时间,打印多长时间前发生的时间/天/周

angular - 从管道更改语言时如何更改日期格式

c# - OR LIKE sql查询 bool 错误

c# - 本地 IIS 无法连接本地数据库

sql-server - 通过比较 4 个不同的行来提取数据

sql-server - T-SQL - #tempimport 在哪里?

sql - 无法对 SQL Server 中的所有行应用计算

sql - 选择所有列,但将列更改为字符串

sql - 输出插入的 T-SQL

Android:如何将密码/安全添加到手机的时间/日期设置以防止用户更改它