简体   繁体   English

将 nvarchar 转换为日期时间

[英]Cast/Convert nvarchar to datetime

i have table:我有桌子:

id   timestamp
1    31.10.2020 16:32:11
2    09.09.2020 09:15:49
3    22.04.2020 02:48:15

Table have huge amount these data.表中有大量这些数据。 Column timestamp is data type "nvarchar".列时间戳是数据类型“nvarchar”。 And i need to sort datas by date or use in clauses WHERE for constraint by date, so i need to convert "timestamp" to datetime.而且我需要按日期对数据进行排序或在 WHERE 子句中使用按日期进行约束,因此我需要将“时间戳”转换为日期时间。 But I can't.但我不能。 I tried convert and cast but still failed.我尝试转换和转换,但仍然失败。

Any advice?有什么建议吗?

Thx.谢谢。

您可以使用convert()格式 104 显式转换为datetime

select convert(datetime, '31.10.2020 16:32:11', 104)

Fix your design, and change the column to a date and time data type.修复您的设计,并将列更改为日期和时间数据类型。 Considering your data is accurate to 1 second, a datetime2(0) seems appropriate here.考虑到您的数据精确到 1 秒, datetime2(0)在这里似乎合适。 First we need to change the "format" of the nvarchar value to an ISO format.首先,我们需要将nvarchar值的“格式”更改为 ISO 格式。 We're going to use the ISO8601 format (yyyy-mm-ddThh:mi:ss.mmm) as it's unambiguous:我们将使用 ISO8601 格式 (yyyy-mm-ddThh:mi:ss.mmm),因为它是明确的:

UPDATE dbo.YourTable
SET [timestamp] = CONVERT(nvarchar(20),TRY_CONVERT(datetime2(0), [timestamp], 4), 126);

Now you can ALTER the table and change the data type to a datetime2(0) :现在您可以ALTER表并将数据类型更改为datetime2(0)

ALTER TABLE dbo.YourTable ALTER COLUMN [timestamp] datetime2(0) NULL;

I also recommend using a different name than timestamp for your column.我还建议为您的列使用与timestamp不同的名称。 timestamp is a deprecated synonym for rowversion , so it's use can make it quite confusing; timestamprowversion已弃用的同义词,因此它的使用可能会使它变得非常混乱; especially as rowversion is not a date and time value but a binary value and cannot be converted to a date and time data type.特别是因为rowversion不是日期和时间值而是binary值,并且不能转换为日期和时间数据类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM