SQL Server:插入日期返回错误的值

时间:2017-02-20 20:05:15

标签: sql sql-server

当我尝试从另一个表中插入信息时,它会从date列返回'1900-01-01',当它应为空时。在导入表上,数据类型为varchar,并且在表中我要将信息插入其中是date数据类型。 EndDate列中有一些空值应插入为空,但它返回'1900-01-01'

Insert into tblServiceHistory (PersonID, PositionID, CommitteeID,StartDate, EndDate)
    Select distinct 
        PersonID, PositionID, CommitteeID, StartDate, EndDate
    From 
        tblCommitteeOfficers_IMPORT 
    Where 
        PersonID is not null
        And StartDate is not null
        And PositionID is not null
        And CommitteeID is not null

1 个答案:

答案 0 :(得分:2)

转换为日期的空字符串会转到'1900-01-01'

e.g。 select convert(date,'')会返回'1900-01-01'

您可以使用nullif()将空字符串转换为null中的select值。

试试这个:

Insert into tblServiceHistory (PersonID, PositionID, CommitteeID,StartDate, EndDate)
Select distinct PersonID, PositionID, CommitteeID, nullif(StartDate,''), nullif(EndDate,'')
From tblCommitteeOfficers_IMPORT 
Where PersonID is not null
  AND nullif(StartDate,'') is not null
  AND PositionID is not null
  AND CommitteeID is not null