[英]Datetime! Conversion failed when converting date and/or time from character string
I tried converting a column with timestamp from nvarchar
to datetime
(as I wasn't sure that by exporting Excel to SQL Server the precision within timestamp won't be lost), but the column still won't convert, showing the same error all the time我尝试将带有时间戳的列从
nvarchar
转换为datetime
(因为我不确定通过将 Excel 导出到 SQL Server,时间戳内的精度不会丢失),但该列仍然无法转换,显示相同的错误时间
Conversion failed when converting date and/or time from character string - convert
从字符串转换日期和/或时间时转换失败 - 转换
I tried我试过
alter table X
alter column [Timestamp] datetime
and I also tried:我也试过:
convert(datetime, [Timestamp], 103)
try_convert(datetime, [Timestamp], 103)
cast ([Timestamp] as datetime)
still no progress.仍然没有进展。
This is the sample data from the column:这是列中的示例数据:
2019-02-13-13.01.05.6100000015
2019-02-18-13.10.46.4850000015
Could you please help?能否请你帮忙?
You can try this:你可以试试这个:
select
try_convert(datetime2(7),
STUFF(STUFF(REPLACE('2019-02-18-13.10.46.485000015','.',':'), 11, 1, ' '),20,1,'.')
,121)
It's probably best to change the type to a DATETIME2 since it has a higher precision than DATETIME.最好将类型更改为DATETIME2,因为它比 DATETIME 具有更高的精度。
First change the format of the timestamp strings to a format that can be casted to a DATETIME2
without problem.首先将时间戳字符串的格式更改为可以毫无问题地转换为
DATETIME2
的格式。
UPDATE X
SET [Timestamp] = CONCAT(LEFT([Timestamp],10), 'T', REPLACE(SUBSTRING([Timestamp],12,8),'.',':'), '.', SUBSTRING([Timestamp],21,9))
WHERE [Timestamp] LIKE '[12][0-9][0-9][0-9]_[01][0-9]_[0-3][0-9]_[0-2][0-9].[0-6][0-9].[0-6][0-9].[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%';
Then double check if there are still some that can't be casted as-is.然后仔细检查是否还有一些不能按原样投射。
SELECT COUNT(*) Errors, MAX([Timestamp]) Example
FROM X
WHERE TRY_CAST([Timestamp] AS DATETIME2) IS NULL;
If the count was 0 then the type of the column can be changed.如果计数为 0,则可以更改列的类型。
ALTER TABLE X
ALTER COLUMN [Timestamp] DATETIME2(7);
A test on rextester here在这里对 reextester 进行测试
Do notice that some precision will be lost.请注意,会丢失一些精度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.