1

I am trying to retrieve Two Columns; App_ID & App_Slot from a table su_Appointments from an sql server database using vb, and I have two conditions the Date and Time; App_Date & App_Time for the query, now when I run the query it throws an error saying : Incorrect syntax near '2014'. The query is as follows I am going to store App_ID into the variable AP_ID

CODE

 Using Query As New SqlCommand("Select App_ID From su_Appointments Where (App_Date = ' and  App_Time = ' )" & DT & TM, sqlcon)
   sqlcon.Open()
   Dim dr As SqlDataReader = Query.ExecuteReader()
   While dr.Read()
   AP_ID = dr(0)
   End While
End Using
sqlcon.Close()
Ullas
  • 11,450
  • 4
  • 33
  • 50

1 Answers1

2

Well, your syntax is effectively wrong

A SELECT statement requires

SELECT <fieldA>, <FieldB>, .... 
FROM <Table> 
WHERE <FieldX> = <Condition1> AND <FieldZ> = <Condition2>

But, a part from this basic error, you need to start using a parameterized query approach

Using sqlcon = new SqlConnection(.....connectionstring...)
    Dim cmdText = "Select App_ID From su_Appointments Where App_Date =@dt and App_Time = @tm" 
    Using Query = New SqlCommand(cmdText, sqlcon)
       sqlcon.Open()
       Query.Parameters.AddWithValue("@dt", DT)
       Query.Parameters.AddWithValue("@tm", TM)
       Using dr =Query.ExecuteReader()
           While dr.Read()
             AP_ID = dr(0)
           End While
       End Using
    End Using
End Using

With a parameterized query, you get many benefits. There is no possibility of Sql Injection Attacks, the text of your command is more clear and understandable, the parameters are treated for correct quoting by the code itself so you don't need to check for single quotes inside your strings, or format correctly dates and decimal numbers.

Eventually, you could encounter a different problem. If your columns App_Date and App_Time are of type datetime then you need to pass parameters of the appropriate type, not simply strings. Instead if, these fields are of type nvarchar (or some other kind of text type) then you pass strings but you will have problems storing and querying correctly in these fields.

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286