0

请看下面的数据库结构:

CREATE TABLE TestStartDate (PersonID int, StartDate datetime NOT NULL)
INSERT INTO TestStartDate VALUES(1,'1899-12-30')

和下面的代码:

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim objCommand As SqlCommand, objCommand2 As SqlCommand
        Dim objCon As SqlConnection
        Try
            objCommand = New SqlCommand
            Using objCommand
                Dim strConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True;MultipleActiveResultSets=true"
                objCon = New SqlConnection
                Using(objCon)
                    objCon.ConnectionString = strConString
                    objCon.Open()
                    objCommand.Connection = objCon
                    objCommand.CommandText = "select startdate from TestStartDate "
                    Dim objDR As SqlDataReader = objCommand.ExecuteReader
                    If objDR.HasRows Then
                        objDR.Read()
                        Using objCon
                            objCommand2 = New SqlCommand
                            Using objCommand2
                                objCommand2.Connection = objCon
                                objCommand2.CommandText = "INSERT INTO TestStartDate (StartDate) VALUES (@StartDate)"
                                objCommand2.Parameters.AddWithValue("@StartDate", DateValue(objDR("StartDate"))) 'line 24
                                'objCommand2.Parameters.AddWithValue("@StartDate", objDR("StartDate")) 'line 25
                                objCommand2.ExecuteNonQuery() 'Line 26
                                Dim date1 As Date = objDR("startdate")
                            End Using
                        End Using
                    End If
                End Using
            End Using
        Catch ex As Exception
            Throw
        Finally

        End Try
    End Sub

代码在第 26 行抛出异常(第 26 行有注释):

SqlDateTime 溢出。必须在 1753 年 1 月 1 日上午 12:00:00 到 9999 年 12 月 31 日晚上 11:59:59 之间

我可以通过注释掉第 24 行并取消注释第 25 行来解决此问题。为什么会DATEVALUE导致此异常?

我查看了以下网页:http: //msdn.microsoft.com/en-us/library/6d6k22a5%28v=vs.80%29.aspx。这表明 DATEVALUE 可能正在将 30/12/1899 转换为 01/01/01(01/01/01 在 SQL Server 中不是可接受的值)?如果是这种情况,那么为什么 30/12/1899 转换为 01/01/01?

4

0 回答 0