0

我目前正在更新我们的数据库系统,其中日期字段位于 nvarchar (20) 中,但是我已将其更改为 smalldatetime。但这样做时,某些日期会从11/12/2014-------> 12/11/2014

Old Date  ------------------------ New Date
11/12/2014------------------------ 2014-11-12 00:00:00.000
12 December 2014------------------ 2014-12-12 00:00:00.000
15/12/2014------------------------ 2014-12-15 00:00:00.000
15/12/2014------------------------ 2014-12-15 00:00:00.000
15 December 2014------------------ 2014-12-15 00:00:00.000
15/12/2014------------------------ 2014-12-15 00:00:00.000
15/12/2014------------------------ 2014-12-15 00:00:00.000
15/12/2014------------------------ 2014-12-15 00:00:00.000
16 December 2014------------------ 2014-12-16 00:00:00.000
16 December 2014------------------ 2014-12-16 00:00:00.000

The following is the code which i am using;

WITH CreateDt1
AS
(
SELECT '14 DEC 12' AS OriginalDate
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/04/2006 17:17:19' 
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)
                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
FROM fct_Project;

有什么办法可以改变吗?

4

1 回答 1

0

让您的数据保持一致,然后应用转换/转换。

DECLARE @dates TABLE (
    DateString VARCHAR(50)
    ,[Date] DATE
)
INSERT INTO @dates (DateString) SELECT '11/12/2014'
INSERT INTO @dates (DateString) SELECT '12 December 2014'
INSERT INTO @dates (DateString) SELECT '15/12/2014'


UPDATE @dates
SET [Date]=
    CONVERT(DATE,
        REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(DateString,
            ' January ','/01/'),
            ' February ','/02/'),
            ' March ','/03/'),
            ' April ','/04/'),
            ' May ','/05/'),
            ' June ','/06/'),
            ' July ','/07/'),
            ' August ','/08/'),
            ' September ','/09/'),
            ' October ','/10/'),
            ' November ','/11/'),
            ' December ','/12/')
    ,103)

SELECT * FROM @dates
于 2019-03-11T15:44:15.917 回答