2013-02-07 25 views
0

我試圖從calender中選擇日期從asp.net到Microsoft SQL數據庫。插入日期時間從asp.net中的日曆到microsoft sql問題

當我選擇像01/04/2012時間的工作,而是試圖插入30/01/2012我得到消息時:

一個char數據類型到datetime數據類型的轉換導致 的OUT-範圍內的日期時間值。

當我創建datetime目的是通過使用C#closeDateCalender.SelectedDate, 代碼是:

sb.AppendFormat("Values('{0}', '{1}' ,'{2}', '{3}','{4}','{5}','{6}','{7}')", 
    opportunity.UserId, 
    opportunity.AccountId, 
    opportunity.OpportunityName, 
    opportunity.CloseDate, 
    opportunity.Stage, 
    opportunity.Probability, 
    opportunity.Amount, 
    opportunity.Description); 
String prefix = "INSERT INTO Opportunities " + "([User_Id],Account_Id,Opportunity_Name,Close_Date,Stage,Probabilty,Amount,[Description])"; 
     command = prefix + sb.ToString(); 

任何知道如何解決它???

回答

0

您的服務器設置爲接受美式格式而非歐式格式的日期。如果您重新格式化日期,以便它的格式爲yyyy-MM-dd,它將起作用。

試試這個:

sb.AppendFormat("Values('{0}', '{1}' ,'{2}', '{3}','{4}','{5}','{6}','{7}')", 
    opportunity.UserId, 
    opportunity.AccountId, 
    opportunity.OpportunityName, 
    opportunity.CloseDate.ToString("yyyy-MM-dd"), 
    opportunity.Stage, 
    opportunity.Probability, 
    opportunity.Amount, 
    opportunity.Description); 
1

要擺脫掉格式化和其他東西的這一切痛苦,使用準備好的statemnts或參數化查詢相反,它會利用所有這格式化的東西照顧。喜歡的東西:

string YourSQL = "INSERT INTO Tablename(columns list) Values(?, ?, ?, ..) "; 

command.Parameters.Add("CloseDate", 
         DbType.DateTime).Value = opportunity.CloseDate; 
... 
...// do the same for the rest of the fields. 

這樣的opportunity.CloseDate應該是數據類型爲DateTime的。