sql-serverssis

Varchar to Date in SSIS


I'm trying to convert a varchar date in the format 2023-01-02T00:00 to DT_DBTIMESTAMP in SSIS. Currently, I’m using this expression in a Derived Column Transformation: (DT_DBTIMESTAMP)(SUBSTRING([start_at], 1, 4) + "-" + SUBSTRING([start_at], 6, 2) + "-" + SUBSTRING([start_at], 9, 2) + " " + SUBSTRING([start_at], 12, 5) + ":00")

This works fine, but it fails when encountering NULL values. To handle NULLs, I tried modifying the expression as follows: ISNULL([start_at]) ? NULL(DT_DBTIMESTAMP) : (DT_DBTIMESTAMP)(SUBSTRING([start_at], 1, 4) + "-" + SUBSTRING([start_at], 6, 2) + "-" + SUBSTRING([start_at], 9, 2) + " " + SUBSTRING([start_at], 12, 5) + ":00")

However, this expression isn’t working as expected. Any suggestions on handling NULL values in this conversion?


Solution

  • Personally, I would recommend using a dbtimestamp2, which maps to datetime2. Converting your string to that is significantly easier; replace the T with a space and then add the seconds on:

    (DT_DBTIMESTAMP2,0) (REPLACE(DateString,"T"," ") + ":00")
    

    DateString in this case if your column containing your (W)STR date formatted in the style yyyy-MM-ddThh:mm.

    There's no need to handle the NULL values explicitly either, as a NULL will result in NULL, as can be seen in the below screenshot of the Data Viewer:
    Data Viewer showing DateString and DateValue columns converted approriately