SQL Server 2008:日期转换问题

时间:2019-03-11 08:38:35

标签: sql sql-server sql-server-2008 nvarchar smalldatetime

我当前正在更新日期字段为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;

有什么办法可以改变它?

1 个答案:

答案 0 :(得分: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