2

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

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

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

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

4

2 回答 2

4

您可以在纯 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
于 2012-09-21T16:47:08.723 回答
1

CndiedCode 链接中的示例非常接近您的需要。

只是略有不同的正则表达式匹配

N'^\d{3}-\d{2}-\d{4}$'
转到
N'\d{2}/\d{2}/\d{2,4}'

下面的代码看起来不同,因为必须转义 \

    if (Regex.IsMatch("sent on 01/01/10; ex", "\\d{2}/\\d{2}/\\d{2,4}"))
    {
        System.Diagnostics.Debug.WriteLine(Regex.Match("sent on 01/01/10; ex", "\\d{2}/\\d{2}/\\d{2,4}"));
    }
    if (Regex.IsMatch("sent on 01/01/2012; ex", "\\d{2}/\\d{2}/\\d{2,4}"))
    {
        System.Diagnostics.Debug.WriteLine(Regex.Match("sent on 01/01/2012; ex", "\\d{2}/\\d{2}/\\d{2,4}"));
    }
于 2012-09-21T15:36:04.240 回答