2014-11-21 89 views
1

我試圖使用SQL CONVERT命令將VARCHAR轉換爲SQL Server 2012中的DATETIME。我按照說明操作,我想使用日期/這個MSDN網頁上描述的時間格式:http://msdn.microsoft.com/en-us/library/ms187928.aspxSQL中將VARCHAR轉換爲DATETIME時出現的問題

在此基礎上,格式#127的描述如下:

  • ISO8601 with time zone Z.
  • yyyy-mm-ddThh:mi:ss.mmmZ (no spaces)
  • When the value for milliseconds (mmm) is 0, the millisecond value is not displayed. For example, the value '2012-11-07T18:26:20.000 is displayed as '2012-11-07T18:26:20'.
  • The optional time zone indicator, Z, is used to make it easier to map XML datetime values that have time zone information to SQL Server datetime values that have no time zone. Z is the indicator for time zone UTC-0. Other time zones are indicated with HH:MM offset in the + or - direction. For example: 2006-12-12T23:45:12-08:00.

然而,當我嘗試實際進行轉換(以下這種格式),它失敗...

SELECT CONVERT(datetime, '2014-07-14T10:00:00.000-08:00', 127) 

...,出現以下錯誤:

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

任何人都知道這是爲什麼不工作?

編輯:例如不工作之一:

SELECT CONVERT(datetime, '2006-12-12T23:45:12-08:00', 127) 

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

回答

1

因爲它是在它時區一個字符串,你需要將其轉換爲DATETIMEOFFSET類型:

SELECT CONVERT(DATETIMEOFFSET, '2014-07-14T10:00:00.000-08:00', 127) 

(No column name) 
---------------------------------- 
2014-07-14 10:00:00.0000000 -08:00 

這工作得很好。一旦你有了,你可以根據需要將它轉換爲當地的DATETIME,例如。與

DECLARE @DateTimeOffset DATETIMEOFFSET 
CAST(@DateTimeOffset AS DATETIME) 

或價值與

SELECT SWITCHOFFSET(@DateTimeOffset, '+01:00') 
+0

切換到另一個時區這工作,謝謝!我想我需要繼續閱讀腳註:-x – 2014-11-21 22:45:20