![](/img/trans.png)
[英]How to convert NVarchar date time to date time format in SQL Server?
[英]How to convert the nvarchar record to date format in SQL?
我有一個表,其中一列設置為nvarchar。 此列稱為bestBefore。 因此,這現在給我們帶來了麻煩,我打算將列類型更改為datetime,但在此之前,記錄如下所示是損壞的:
'Mon Feb 19 23:45:59 EST 2018'
'2017-12-11 20:55:47.831'
'Mon Dec 18 18:51:54 EST 2017'
第二行是我對新記錄的預期。 所以我寫了這樣的東西:-
select top 1000 CONVERT(datetime, bestBefore, 103) from
[dbo].[TestTable] order by id desc
但是我遇到了這個錯誤-“從字符串轉換日期和/或時間時轉換失敗。”
有人能幫我嗎? 如果我可以正確轉換,那么我也許可以更改列類型。
我認為SQL Server不直接支持以下格式掩碼:
Mon Feb 19 23:45:59 EST 2018
但是我們仍然可以拼湊支持的日期格式。 上面帶有109格式掩碼的時間戳將顯示如下:
Feb 19 2018 23:45:59
考慮以下查詢:
-- replace the yourTable CTE with your actual table
WITH yourTable AS (
SELECT 'Mon Feb 19 23:45:59 EST 2018' AS col
),
cte AS (
SELECT
col,
new_col, -- a new datetime column
CONVERT(datetime,
SUBSTRING(col, 5, 3) + ' ' + SUBSTRING(col, 9, 2) + ' ' +
RIGHT(col, 4) + ' ' + SUBSTRING(col, 12, 8), 109) AS col_out
FROM yourTable
)
col col_out
1 Mon Feb 19 23:45:59 EST 2018 19.02.2018 23:45:59
要更新,只需使用以下命令:
UPDATE cte
SET new_col = col_out;
嘗試此操作,對@Tim Biegeleisen的答案進行了一些更改。
DECLARE @bestBefore VARCHAR(50)='2017-12-11 20:55:47.831'
IF((SELECT LEFT(@bestBefore,1)) IN('S','M','T','W','F'))
BEGIN
SELECT
CONVERT(datetime,
SUBSTRING(@bestBefore, 5, 3) + ' ' + SUBSTRING(@bestBefore, 9, 2) + ' ' +
RIGHT(@bestBefore, 4) + ' ' + SUBSTRING(@bestBefore, 12, 8), 109) AS col_out
END
ELSE
BEGIN
SELECT @bestBefore
END
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.