Converting a string data type into a Datetime data type in SSIS can be done using SQL such as CONVERT(DATETIME, [stringcolumn], 112). But if the source is a flat file or an Excel file, the conversion is usually made using a Derived Column Transformation.
An 8-digit string usually does not present any problem. In SQL Server the most common recommendation is not to use the YYYY-MM-DD format for date literals; always use YYYYMMDD. For example:
SELECT CAST([NumericStringColumn] AS datetime) |
where [NumericStringColumn] might have a value such as ‘20131231’
In SQL Server this will never fail, regardless of locale, dateformat settings, language settings, regional settings, etc. However, date and time format is relevant when the date and time value is a string. The dateformat and language of the database or server decides how to parse the string value to internally represent and store the datetime value. You can identify the language and dateformat configured in your SQL Server by executing the following command.
DBCC USEROPTIONS WITH NO_INFOMSGS |
(You may want to read read Tibor Karazsi's article The ultimate guide to the datetime datatypes which discusses the handling of Dates in SQL Server.) Just keep in mind that SSIS handles Dates a little differently. In SSIS Dates represented as a numeric string value are handled differently. SSIS will not convert a numeric string to a Datetime data type; But, if you have an 8-digit string, just add a dash or slash in the appropriate places using a Derived Column Transformation and it will work.
But 6-digit strings require a little more caution. Assume we have a 6-digit string that we want to convert to a Datetime data type using a Derived Column Transformation. We can add a slash or a dash in the appropriate places and the result may or may not be the result we are looking for. For example if we have a string with a value of 130326 (or 032613) and language in SQL Server is set at “us_english” and dateformat is set as “mdy” and we use the following expression in the Derived Column Transformation,
ISNULL(SixDigitStringColumn) ? NULL(DT_DBTIMESTAMP) : SUBSTRING(SixDigitStringColumn,1,6) == "000000" ? NULL(DT_DBTIMESTAMP) : TRIM(SixDigitStringColumn) == "" ? NULL(DT_DBTIMESTAMP) : (DT_DBTIMESTAMP)(SUBSTRING(SixDigitStringColumn,1,2) + "-" + SUBSTRING(SixDigitStringColumn,3,2) + "-" + SUBSTRING(SixDigitStringColumn,5,2)) |
We will get a value of 2013-03-26 00:00:00.000. However, if our string has a value of 032601, we will get a value of 2001-03-26 26 00:00:00.000. To avoid unexpected results, it is best to always add the century to a 6-digit string.