0

I am trying to run an SQL query in my vb.net application using a loop

SQL = "SELECT * FROM table WHERE "
For m = 1 To num_array
    SQL = SQL & "type = '" & array(m, 1) & "' OR "
Next

but its showing an OR at the end.

how can i trim this last OR from my query?

2
  • 3
    Don't do this. Use parameterized queries instead. otherwise you are risking sql injection attacks. Apr 6, 2016 at 15:07
  • Those types of SQL engines/parameter helpers rarely simplify code Apr 6, 2016 at 17:09

1 Answer 1

3

This seems a job for a StringBuilder

Dim sql = new StringBuilder("SELECT * FROM table WHERE ")
For m = 1 To num_array
    sql.Append("type = '" & array(m, 1) & "' OR ")
Next

If num_array > 0 Then
    sql.Length -= 4
End If

However you should pay special care to your string concatenation. It seems that your array doesn't contain numbers but string because you are putting everything between single quotes and this means that your type field is a string not a number.
Of course I hope that your array content is not directly inserted by your user otherwise you have a big security risk called Sql Injection. Anyway look at how to build a parameterized query.

Something like this

Dim prms = New List(Of SqlParameter)()
Dim num_Array = 4
Dim sql = New StringBuilder("SELECT * FROM table WHERE ")
For m = 1 To num_array
    sql.Append("type = @p" & m & " OR ")
    prms.Add(New SqlParameter("@p" & m, array(m, 1)))
Next

If num_array > 0 Then
    sql.Length -= 4
End If 
Dim cmd = new SqlCommand(sql.ToString(), connection)
cmd.Parameters.AddRange(prms.ToArray())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.