SQL Server 2008:日期转换问题

问题描述 投票:0回答:1

我正在更新我们的数据库系统,其中日期字段在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;

这有什么方法可以改变吗?

sql sql-server sql-server-2008 nvarchar smalldatetime
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
© www.soinside.com 2019 - 2024. All rights reserved.