SQL Server:如果“datetime2”< 1753,然后“datetime”为NULL?

时间:2011-04-12 13:40:41

标签: sql sql-server tsql sql-server-2008

我的目的是将源表中的数据插入目标表。源表有datetime2列,目标表有datetime列。如果datetime2值不适合(<1753年)到datetime字段,则会转换为null。这是一个例子

DROP TABLE dbo.test1
--source table
CREATE TABLE dbo.test1 (wday DATETIME2 NULL)
go

INSERT  INTO dbo.test1
        (wday
        )
        SELECT  '2008-02-01 00:00:00.000'
        UNION ALL
        SELECT  '2009-02-01 00:00:00.000'
        UNION ALL
        SELECT  '0001-02-01 00:00:00.000'

DROP TABLE dbo.test2
--target table
CREATE TABLE dbo.test2 (wday DATETIME NULL)
go

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEDIFF(YEAR, dbo.test1.wday, GETDATE()) < 111
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1

代码不起作用。另外在这里使用datediff是无效的逻辑,如何实现呢?

2 个答案:

答案 0 :(得分:3)

为什么不只是

INSERT  dbo.test2
        (wday
        )
        SELECT  CASE WHEN dbo.test1.wday < '17530101'
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1

答案 1 :(得分:1)

另一种选择:

--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
        (wday
        )
        SELECT  CASE WHEN DATEPART(YEAR, dbo.test1.wday) < 1753
                     THEN NULL
                     ELSE CAST(dbo.test1.wday AS DATETIME)
                END
        FROM    dbo.test1