我正在使用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中的引号来比较Date列?但后来我没有得到异常,但结果不正确。
答案 0 :(得分:1)
是的,应该删除引号。你永远不应该在T-SQL中引用参数 - 即使在使用字符串时也是如此。因此,您应该删除@SSN_Number
和@Repair_Completion_Date
周围的引号。