【问题标题】:How to convert nvarchar timestamp to datetime2 in SQL Server?如何在 SQL Server 中将 nvarchar 时间戳转换为 datetime2?
【发布时间】:2020-07-02 21:47:06
【问题描述】:

我已将我的数据移动到临时表中,并最终将这些数据插入到我的主表中。我在将 nvarchar 转换为 datetime2 时遇到问题。我的 nvarchar 日期时间列的值如下所示: 2019-04-02T12:45:47.000-0400 。我想将其转换为 datetime2 - 2019-04-02 12:45:47.0000000 。

我怎么能做到这一点,因为简单地改变表格对我不起作用?

【问题讨论】:

  • SQL Server 有一堆字符串和转换函数,它们结合起来应该可以完成这项工作。

标签: sql-server casting datetime2


【解决方案1】:

您使用的日期/时间字符串的格式不能直接转换为 datetime2 或 datetimeoffset。如果您没有时区偏移量,您可以使用convert(datetime2, '2019-04-02T12:45:47.000', 126)

如果您想保持时区偏移,请尝试以下操作...

use StackOverflow;
go
drop table if exists dbo.Staging;
create table dbo.Staging (
  Foo varchar(30)
);

drop table if exists dbo.Main;
create table dbo.Main (
  Bar datetime2,
  Baz datetimeoffset
);

insert dbo.Staging values ('2019-04-02T12:45:47.000-0400');

-- 1. Replace the 'T' with space(1)
-- 2. Reformat the timezone offset (note the space before the sign)
update dbo.Staging
set Foo = replace(replace(Foo, 'T', ' '), '-0400', ' -04:00');

insert dbo.Main (Bar, Baz)
  select cast(Foo as datetime2), cast(Foo as datetimeoffset)
  from dbo.Staging;

select * from dbo.Main;

哪个产生...

Bar                         Baz
--------------------------- ----------------------------------
2019-04-02 12:45:47.0000000 2019-04-02 12:45:47.0000000 -04:00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2022-12-02
    • 1970-01-01
    • 2016-11-30
    • 2014-03-01
    • 2010-09-23
    • 1970-01-01
    相关资源
    最近更新 更多