截图说明了一切。 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/