转换失败:SqlParameter 和 DateTime
我正在使用 SqlParameters 更改旧的、易受攻击的 SqlCommands,但收到 SqlException:
System.Data.SqlClient.SqlException {“从字符串转换日期时间时转换失败。”}
on sqlCommand.ExecuteScalar
:
Dim sqlString As String = _
"SELECT TOP 1 " & _
"fiSL " & _
"FROM " & _
"tabData AS D " & _
"WHERE " & _
"D.SSN_Number = '@SSN_Number' " & _
"AND D.fiProductType = 1 " & _
"AND D.Repair_Completion_Date > '@Repair_Completion_Date' " & _
"ORDER BY " & _
"D.Repair_Completion_Date ASC"
Dim obj As Object
Dim sqlCommand As SqlCommand
Try
sqlCommand = New SqlCommand(sqlString, Common.MyDB.SqlConn_RM2)
sqlCommand.CommandTimeout = 120
sqlCommand.Parameters.AddWithValue("@SSN_Number", myClaim.SSNNumber)
sqlCommand.Parameters.AddWithValue("@Repair_Completion_Date", myClaim.RepairCompletionDate)
If Common.MyDB.SqlConn_RM2.State <> System.Data.ConnectionState.Open Then Common.MyDB.SqlConn_RM2.Open()
obj = sqlCommand.ExecuteScalar()
Catch ex As Exception
Dim debug As String = ex.ToString
Finally
Common.MyDB.SqlConn_RM2.Close()
End Try
myClaim.RepairCompletionDate
是 SQLDateTime。 我是否必须删除 sqlString 中的引号才能比较日期列?但后来我没有得到异常,但结果不正确。
I'm changing old, vulnerable SqlCommands with SqlParameters but get a SqlException:
System.Data.SqlClient.SqlException {"Conversion failed when converting datetime from character string."}
on sqlCommand.ExecuteScalar
:
Dim sqlString As String = _
"SELECT TOP 1 " & _
"fiSL " & _
"FROM " & _
"tabData AS D " & _
"WHERE " & _
"D.SSN_Number = '@SSN_Number' " & _
"AND D.fiProductType = 1 " & _
"AND D.Repair_Completion_Date > '@Repair_Completion_Date' " & _
"ORDER BY " & _
"D.Repair_Completion_Date ASC"
Dim obj As Object
Dim sqlCommand As SqlCommand
Try
sqlCommand = New SqlCommand(sqlString, Common.MyDB.SqlConn_RM2)
sqlCommand.CommandTimeout = 120
sqlCommand.Parameters.AddWithValue("@SSN_Number", myClaim.SSNNumber)
sqlCommand.Parameters.AddWithValue("@Repair_Completion_Date", myClaim.RepairCompletionDate)
If Common.MyDB.SqlConn_RM2.State <> System.Data.ConnectionState.Open Then Common.MyDB.SqlConn_RM2.Open()
obj = sqlCommand.ExecuteScalar()
Catch ex As Exception
Dim debug As String = ex.ToString
Finally
Common.MyDB.SqlConn_RM2.Close()
End Try
myClaim.RepairCompletionDate
is a SQLDateTime.
Do i have to remove the quotes in the sqlString to compare Date columns? But then i dont get a exception but incorrect results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,应该删除引号。永远不应该在 T-SQL 中的参数周围使用引号 - 即使使用字符串时也是如此。因此,您应该删除
@SSN_Number
和@Repair_Completion_Date
周围的引号。Yes, the quotes should be removed. You should never have quotes around parameters in T-SQL - not even when using strings. Hence, you should remove the quotes around
@SSN_Number
and@Repair_Completion_Date
.