我的目的是将源表中的数据插入目标表。源表有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
是无效的逻辑,如何实现呢?
答案 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