I am building up an SQL query in VB.net and have written a routine to do it dynamically.
I want to include each item in an array (of unknown size) in the where clause, as such:
Dim person(10) as String
Dim strSQL, strWhereClause as String
person(0) = "John"
person(1) = "Steve"
'...
For i = 0 To UBound(menuNames)
strWhereClause &= "[name] = '" & person(i) & "' OR "
Next
strSQL= "SELECT * FROM [customers] WHERE " & strWhereClause
The problem here is that there is an extra " OR " at the end. Is there a neat way of removing this? Or perhaps a better way to approach the problem all together. (I think a string.join will not work in this situation, because there is text before and after the array item.)
EDIT: Manually removing the final three characters like so:strWhereClause = Left(strWhereClause, strWhereClause.Length - 3) is fine, except it doesn’t handle the empty string. After all, I don’t know how many elements will be in my array.
You should not do this in the way you do, even if you are 100% sure what contents are stored in the array it is still a bad habit. Instead you should get yourself familiar using parameterized queries.
Not compile-tested:
Assuming you SqlCommand is
command.Sorry for the C# but my VB is too rusty, i hope you get the point. 😉