請看看下面的數據庫結構:DateValue和SQL DATETIME - 30/12/1899轉換爲01/01/01?
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 AM和12/31/9999之間下午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?
兩種可能性:由'objDR'產生的日期時間值超出範圍,或在'DateValue'轉換期間變爲無效。 DateValue(objDR(「StartDate」))產生什麼值?你有沒有嘗試通過編寫'objDR.GetDateTime(objDR.GetOrdinal(「StartDate」))'來替換'DateValue'函數? – stakx 2013-03-24 13:06:28
@stakx,我編輯了這個問題,請再看一下。 – w0051977 2013-03-24 13:12:03
用'1899年日期功能'檢查這個鏈接的一些歷史記錄:http://stackoverflow.com/questions/3963617/why-is-1899-12-30-the-zero-date-in-access-sql -server-instead-of-12-31 – 2013-03-24 13:20:16