我目前正在更新公司数据库,其中在一个表中,CreateDt
的类型为nvarchar(20)
,并通过以下方式存储日期:
12 May 12 29/03/2011 9/24/2012 29/01/2001 08:51:56
有17,000行。
因此,我目前正在研究将这些日期全部转换为DD-MM-YYYY
之类的一种格式的代码。
但是我正在努力寻找合适的东西。
到目前为止,我已经尝试过:
WITH CreateDt1
AS
(
SELECT '14 DECEMBER 12' AS CreateDt1
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/05/2002 09:28:58'
UNION ALL
SELECT '28/02/2011'
)
SELECT
CreateDt1,
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (CreateDt1, 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (CreateDt1, 4) AS datetime)
END
END
END AS NewDate
FROM fct_Project;
但是,对于诸如29/01/2001 08:51:56
之类的日期,它将返回空值。
答案 0 :(得分:0)
我刚刚添加了几行来编辑您的代码,希望对您有所帮助。 请记住,它不能解决10/11和11/10的问题。
WITH CreateDt1
AS
(
SELECT '14 DECEMBER 12' AS CreateDt1
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/05/2002 09:28:58'
UNION ALL
SELECT '28/02/2011'
)
SELECT
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (CreateDt1, 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (CreateDt1, 4) AS datetime)
WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + LEFT((RIGHT (CreateDt1, 13)),4) ) = 1
THEN CAST ( (SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + LEFT((RIGHT (CreateDt1, 13)),4) ) AS DATETIME)
END
END
END AS NewDate
FROM CreateDt1;
答案 1 :(得分:0)
尝试在case子句中向查询中添加RIGHT的LEFT函数:
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (LEFT(CreateDt1,10), 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (LEFT(CreateDt1,10), 4) AS datetime)
END
END
END AS NewDate