I'm trying to select a certain number of records from an Access table using VB.Net, however I'm having trouble setting the parameters. The code is listed below:
Dim sqlQry As String
Dim iNumber As Integer = Convert.ToInt32(txtNoMemberships.Text)
sqlQry = "SELECT TOP @MemberNo [ID] FROM tblMembership WHERE [Taken] IS NULL"
Dim objConn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Try
objConn.ConnectionString = dbConnection
objConn.Open()
cmd.Connection = objConn
cmd.CommandText = sqlQry
cmd.Parameters.AddWithValue("@MemberNo", iNumber)
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If I change sqlQry to something like "SELECT 5 [ID] FROM tblMembership WHERE [Taken] IS NULL" then the command runs fine and I get no debug. But if I try to use parameters, I get the error:
The SELECT statement includes a reserved word or argument name that is misspelled or missing, or the punctuation is incorrect.
I know I could get away with it doing the following, but i thought it's best to err on the side of caution due to SQL injection:
sqlQry = "SELECT TOP " & iNumber & " [ID] FROM tblMembership WHERE [Taken] IS NULL"