使用数据转换后月份和日期位置互换
Month and date position got interchanged after using Data conversion
我正在尝试将一些数据从 .csv
文件加载到我的 SQL 服务器中。 .csv
文件中有一个数据类型为 Unicode (WSTR) 的日期列,SQL 服务器中用于存储该日期的列是 Datetime
数据类型。
当我使用 DATA CONVERSION 转换将 WSTR 数据转换为 DBTIMESTAMP 数据时,它发生了变化,但出现错误,它交换了月份和日期,这给了我错误的日期。
日期应该是 2019-09-03(2019 年 9 月 3 日),但我得到的是 2019-03-09。
请指出我面临的问题是什么?
问题
在未指定日期格式的情况下将字符串转换为日期值时可能会发生这种情况。参考 SSIS data conversion transformation official documentation:
If you are converting data to a date or a datetime data type, the date in the output column is in the ISO format, although the locale preference may specify a different format.
假设数据以以下日期格式存储在csv文件中MM/dd/yyyy
,并且区域设置中的默认日期格式为dd/MM/yyyy
,则日期值将无法正确转换。
解决方案
为了指定日期格式,您必须使用脚本组件或派生列。
派生列
你必须手动重新排序日期部分,你可以使用 TOKEN()
和 TOKENCOUNT()
函数来做到这一点,下面的表达式将 dd/MM/yyyy
格式转换为 yyyy-MM-dd
通用格式:
TOKEN([DateColumn],"/",3) + "-" + RIGHT("0" + TOKEN([DateColumn],"/",2),2) + "-" +RIGHT("0" + TOKEN([DateColumn],"/",1),2)
脚本组件
您可以使用DateTime.ParseExact()
函数根据特定格式解析日期:
DateTime.ParseExact(Row.DateColumn,"MM/dd/yyyy",System.Globalization.CultureInfo.InvariantCulture");
我正在尝试将一些数据从 .csv
文件加载到我的 SQL 服务器中。 .csv
文件中有一个数据类型为 Unicode (WSTR) 的日期列,SQL 服务器中用于存储该日期的列是 Datetime
数据类型。
当我使用 DATA CONVERSION 转换将 WSTR 数据转换为 DBTIMESTAMP 数据时,它发生了变化,但出现错误,它交换了月份和日期,这给了我错误的日期。
日期应该是 2019-09-03(2019 年 9 月 3 日),但我得到的是 2019-03-09。
请指出我面临的问题是什么?
问题
在未指定日期格式的情况下将字符串转换为日期值时可能会发生这种情况。参考 SSIS data conversion transformation official documentation:
If you are converting data to a date or a datetime data type, the date in the output column is in the ISO format, although the locale preference may specify a different format.
假设数据以以下日期格式存储在csv文件中MM/dd/yyyy
,并且区域设置中的默认日期格式为dd/MM/yyyy
,则日期值将无法正确转换。
解决方案
为了指定日期格式,您必须使用脚本组件或派生列。
派生列
你必须手动重新排序日期部分,你可以使用 TOKEN()
和 TOKENCOUNT()
函数来做到这一点,下面的表达式将 dd/MM/yyyy
格式转换为 yyyy-MM-dd
通用格式:
TOKEN([DateColumn],"/",3) + "-" + RIGHT("0" + TOKEN([DateColumn],"/",2),2) + "-" +RIGHT("0" + TOKEN([DateColumn],"/",1),2)
脚本组件
您可以使用DateTime.ParseExact()
函数根据特定格式解析日期:
DateTime.ParseExact(Row.DateColumn,"MM/dd/yyyy",System.Globalization.CultureInfo.InvariantCulture");