【问题标题】:SSIS convert string with no 0's to date formatSSIS将没有0的字符串转换为日期格式
【发布时间】:2022-01-07 11:42:37
【问题描述】:

我正在尝试将字符串数据类型转换为在月份和日期部分的字符串中不包含 0 的日期,并且需要将其转换为日期格式 yyyy-MM-dd,任何单个数字将没有零

例如,日期输入为

162022  it should be (01-06-2022)

762022 it should be (07-06-2022)

1262022 it should be (12-06-2022)

如何使用派生列获得正确的格式以将其转换为日期数据类型?

【问题讨论】:

  • 修复源。你怎么知道1122002 是 2 月 11 日还是 12 月 1 日?

标签: sql-server date ssis etl derived-column


【解决方案1】:

尝试使用以下表达式:

LEN([StringColumn]) == 6 ? "0" + LEFT([StringColumn],1) + "-0" + SUBSTRING([StringColumn],2,1) + "-" + RIGHT([StringColumn],4) : 
LEN([StringColumn]) == 8 ? LEFT([StringColumn],2) + "-" + SUBSTRING([StringColumn],3,2) + "-" + RIGHT([StringColumn],4) :
LEN([StringColumn]) == 7 ? 
(DT_I4)SUBSTRING([StringColumn],2,2) > 12 ? LEFT([StringColumn],2) + "-0" + SUBSTRING([StringColumn],3,1) + "-" + RIGHT([StringColumn],4) : "0" + LEFT([StringColumn],1) + "-" + SUBSTRING([StringColumn],2,2) + "-" + RIGHT([StringColumn],4) : [StringColumn]

这个表达式逻辑可以总结如下表

Input length Date Format Example How to convert into date
6 dmyyyy 162021 add zero before the first and second digits
7 dmmyyyy or ddmyyyy 1262021 or 2122021 check if the second and third digits are greater than 12 then consider that the first two digits are for the day part else consider only the first digit for the day
8 ddmmyyyy 01062021 do nothing
< 6 or > 8 ? ? do nothing

这个表达式是有效的,除了像1112021这样的值,不容易预测是日期部分是11还是月份部分是11

【讨论】:

    【解决方案2】:

    您可以尝试暴力破解方法,但如下例所示,可能的日期可能不止 1 个。

    这是一种有风险的格式,需要格外小心。

    示例

    Declare @YourTable Table ([SomeCol] int)  Insert Into @YourTable Values 
     (162022)
    ,(7182022)
    ,(1262022)
    ,(12182022)
    
    Set DateFormat MDY
    
    Select SomeCol
          ,AsDate 
          ,Cnt    = sum(1) over (partition by [SomeCol])
     From  @YourTable A
     Cross Apply ( values ( stuff(reverse(SomeCol),5,0,'-') ) ) B(rStr)
     Cross Apply ( values ( stuff(rStr,7,0,'-') ) 
                         ,( stuff(rStr,8,0,'-') ) 
                         ,( stuff(rStr,9,0,'-') ) 
                 )  C(tStr)
     Cross Apply ( values ( try_convert(date,reverse(tStr)) ) ) D(AsDate)
     Where AsDate is not null
    

    结果

    SomeCol     AsDate      Cnt
    162022      2022-01-06  1
    1262022     2022-01-26  2  <<< Two valid dates
    1262022     2022-12-06  2  <<< Two valid dates
    7182022     2022-07-18  1
    12182022    2022-12-18  1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 2014-01-18
      • 2019-10-13
      相关资源
      最近更新 更多