[英]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.