2013-10-22 69 views
0

不太確定我在這裏做錯了什麼。我有一個來自文本框的字符串,它是一個日期(22/10/2013),我想用它來使用存儲過程從SQL DB中選擇一個值。使用datetime將字符串傳遞給SQL通過存儲過程

的VB代碼:

'gets the values for the daily prices from DB if they exist. 
    Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Optimiser_TestConnectionString").ConnectionString) 
     conn.Open() 
     Using cmd As SqlCommand = conn.CreateCommand 
      cmd.CommandType = CommandType.StoredProcedure 
      cmd.CommandText = "get_dailypricing" 
      cmd.Parameters.Add("@datedisplay", SqlDbType.DateTime).Value = date_select.Text 
      Dim sqlrd As SqlDataReader = cmd.ExecuteReader 

      If sqlrd.HasRows Then 
       sqlrd.Read() 
       Me.date_select.Text = sqlrd.Item("price") 
      Else 
       Me.date_select.Text = "N/A" 
      End If 
     End Using 
    End Using 

存儲過程是:

ALTER procedure [dbo].[get_dailypricing] 
    @DateDisplay date 
AS 
Begin 
    select price 
    from dailyPricing 
    where dateSubmitted = @DateDisplay 
end 

我使用Visual Studio 2012和SQL Server 2012的SQL Server中的日期爲datetime類型的的2013-10-22 11:37:49.727

格式我得到一個錯誤

該字符串未被識別爲有效的DateTime。有一個未知的字從索引0開始

+0

如果你谷歌錯誤,你到那裏沒有結束的SO問題和答案。 [鏈接](http://stackoverflow.com/questions/10625292/the-string-was-not-recognized-as-a-valid-datetime-there-is-an-unknown-word-star)[鏈接]( http://stackoverflow.com/questions/16462510/the-string-was-not-recognized-as-a-valid-datetime-there-is-an-unknown-word-star)[link](http:// stackoverflow.com/questions/17492269/the-string-was-not-recognized-as-a-valid-datetime-there-is-an-unknown-word-star) –

回答

0

你在SQL日期爲DateTime格式,但您的存儲過程的參數是Date數據類型。 您需要像這樣將參數數據類型轉換爲DateTime

@DateDisplay date 
0

的問題是在你的.NET代碼,而不是在SQL Server

在行:

cmd.Parameters.Add("@datedisplay", SqlDbType.DateTime).Value = date_select.Text 

你傳入的日期值作爲一個字符串,而不是DateTime對象。 .NET將嘗試使用當前線程的文化來解析此字符串,這可能無法解析用戶的輸入。

您應該在自己解析之前驗證用戶的字符串,然後將解析的值傳遞給存儲過程。更好的是,使用類似DatePicker的控件只返回有效地址。

假設你想使用線程的語言環境,您應使用此代碼:

Dim theDate=DateTime.Parse(date_select.Text) 
cmd.Parameters.AddWithValue("@datedisplay",theDate) 

更安全的選擇是要求用戶在特定的格式輸入文字,然後使用此格式解析。假設你希望用戶使用InvariantCulture的,你應該寫:

Dim theDate=DateTime.Parse(date_select.Text,CultureInfo.InvariantCulture) 
cmd.Parameters.AddWithValue("@datedisplay",theDate) 
0

感謝指出錯誤在我的存儲過程,但真正的問題是我用的是date_select文本框顯示的價格時,它應當被另一個文本框。我在頁面上有一個圖表,它使用date_select文本框中的日期,因此當它改變了整個頁面時崩潰了。我現在修復了這個問題。

相關問題