Using a VBA array in a SQL statement - sql

I am trying to write some code that uses SQL to delete rows from several tables.
A user would type type numbers into a textbox that are separated by a comma which is used in the WHERE clause of a SQL DELETE statement.
I have managed to split the string into a variant array and now I want to insert it into my SQL statement.
How do I insert the variable into the SQL statement and have it run through every element of the array?
EDIT: A bit more digging has taught me about For Each Next statements. This is probably what im looking for.

I suggest you build your query in VBA, then your list of numbers can be an IN statement:
sSQL = "DELETE FROM table WHERE ID In (" & MyList & ")"
Where MyList = "1,2,3,4" or such like.
As you can see, you do not need an array and a textbox would be more suitable than a combobox. If you wish to allow your users to select by say, a name, then a listbox is useful. You can iterate through the selected items in the listbox and build a string from IDs to be used in the Delete statement. ( MS Access 2007 - Cycling through values in a list box to grab id's for a SQL statement )
You can then execute the sql against an instance of a database. For example:
Dim db As Database
Set db = CurrentDB
db.Execute sSQL, dbFailOnError
MsgBox "You deleted " & db.RecordsAffected & " records."

A generic approach
WHERE
','+Array+',' like '%,'+col+',%'
It will consider all the numbers available in your Array

You could make it simple and elaborate a string, something like
stringBuilder sb = StringBuilder("DELETE FROM YOURTABLE WHERE ");
foreach(string st in stringArray){
sb.append("YOURFIELD='" + st + "'");
//If it is not the last element, add an "OR"
if (st != stringArray[stringArray.length -1]) sb.append(" OR ");
}
//Now, you have a string like
//DELETE FROM YOURTABLE WHERE YOURFIELD='hello' OR YOURFIELD='YES'
//... do something with the command

This method will fail if you want to run SQL query on two (or multiple) columns using array values from two different arrays. .e.g
where col1=array1(i) and col2=array2(i)

Related

MS ACCESS VBA: type mismatch error in recordset name into SQL statement string

How should I write the name of the recordset correctly? I have a type mismatch error on & rsg & at "sq3=..." line. Thanks in advance.
Dim rsG As DAO.Recordset
Dim sq2, sq3 As String
sq2 = "SELECT * from GeneralTable "
sq2 = sq2 & "where gsede='LION' and (gExclu is null) and (gAda is null) "
sq2 = sq2 & "order by gnomb,gnif;"
Set rsG = CurrentDb.OpenRecordset(sq2)
sq3 = "UPDATE " & rsG & " SET gsede ='AA' WHERE gsede='LION'"
DoCmd.RunSQL (sq3)
You are mixing up totally different ways to update data - UPDATE SQL and VBA recordset.
If you want to update a recordset row by row, you do something like
Do While Not rsG.EOF
If rsG!foo = "bar" Then
rsG.Edit
rsG!gsede = "AA"
rsG.Update
End If
rsG.MoveNext
Loop
Do the update using a single query:
update generaltable
set gsede = 'AA'
where gsede ='LION' and (gExclu is null) and (gAda is null);
If you do the update off of rsG, then you'll likely do a separate update for each row, and that is inefficient.
You can't mix and match SQL and recordset objects. You can either build a full update statement that includes the logic of the first select (as other answer suggests), or you can open a dynamic recordset and loop through the records programmatically to make the updates.
That being said, looping through large recordsets programmatically to make updates is usually better handled by a bulk SQL statement, unless it is essential to consider each row individually inside the code - which in your basic example would not be the case.
MS has a good article on the DAO.Recordset object. There is a dynamic-type Recordset example about halfway down.

VB.net - How can I delete an Item in an Access Database?

I'm trying to delete an Item in my Access Database with vb.net
my code is:
Dim DString As String = "DELETE * FROM studentTable WHERE ID='" & DataGridView1.SelectedRows.Item(0).Cells(0).Value & "'"
Dim DCMD As New OleDbCommand(DString, con)
DCMD.ExecuteNonQuery()
Fill()
the code is working fine, my Problem is it's not working because my "ID" Row is set to AutoIncrement. What can I do to fix??
King regards
You have a syntax error in your SQL. You do not need a projection (column list) for a DELETE statement.
Try removing the * such as:
DELETE FROM studentTable WHERE ID=....
Also you do not need to quote numeric values with the apostrophe character (I don't think it will hurt).
You might also want to consider using a parameterized query instead of embedding the value.

Writing Dynamic SQL Statement

I am very new to Microsoft Access.
I would like to select a column from a table based on the value of a parameter (i.e. my table has columns x, y and z and I have a chosencol parameter which is set by the user using a dropdown.
I can select one / all of the columns using a select command, however, I would like to do this using my parameter chosencol instead.
Having read around, I have found a number of references to using the SET and EXEC commands, however, entering them into the SQL command in Access just yields errors.
Please could someone advise me as to how I go about implementing a dynamic-sql query in Access (in fine detail as I think I am writing the commands in the wrong place at the moment...)
First I created an example table in Access.
Next, I created an example form to query your value. The dropdown is called 'chosencol'. Select a value from the Column Select dropdown and press the "Lookup Value" button.
Here is the code under the "Lookup Value" button's On Click event. A SQL statement is dynamically built with the column you chose. The column is renamed to [FieldName] to that it can by referenced.
Private Sub btnLookup_Click()
Dim rsLookup As New ADODB.Recordset
Dim strSQL As String
strSQL = "select " & chosencol.Value & " as [FieldName] from Table1 where ID=1"
rsLookup.Open strSQL, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
If rsLookup.EOF = False Then
txtValue.SetFocus
txtValue.Text = rsLookup![FieldName]
End If
rsLookup.Close
End Sub
When the button is pushed, the value from whatever column you selected will be returned. For this simple example, I'm always returning row 1's data.
I'm pretty sure you can't do that in straight SQL. However, you can create the SQL string in VBA code and save it as a query.
CurrentDB.CreateQueryDef("MyQueryName", "SELECT " & chosencol & " FROM MyTable")
Now, MyQueryName will be a permanent query in your database and can be referenced wherever you want.
If chosencol is a multi-select dropdown, you'll have to read the selected values into an array and then write the array to one concatenated string and use that instead.

MS Access Query from form for multiple records in text box

I have created a form in Access which queries a single record in a set date range. This works beautifully. My question is how can I query multiple records from a form text box.
Something Similar to the SQL function
IN ('XXX','XXX','XXX')
I want my users to be able enter multiple values on the form and it will spit out the corresponding Data.
Try the Split() function. Something like this:
Dim arr() As String
Dim MySQL as String
If Len(Me!MyTextbox) > 1 Then
MySQL = "SELECT * FROM MyTable WHERE MyField in ("
arr = Split(Me!MyTextbox.Text, ",")
For i = LBound(arr) To UBound(arr)
MySQL = MySQL & "'" & arr(i) & "', "
Next
MySQL = Left(MySQL, Len(MySQL) - 2) & ")"
Me.RecordSource = MySQL
Else
MsgBox "There are no values to search for."
EndIf
You would just loop through the array and add each value to a WHERE string. You would have to instruct your users (via a label on the form) to separate values using a comma.
When you want to allow multiple entries it's generally better to have a datasheet subform where users can enter data one per row. Then you use the subform data in queries just like a regular table.

SQL concatenation inside VBA string

I'm using VBA excel 2003,SQL 2005 to make a sql query call and inside my sql statement I'm using '+' operator to concatenate two strings.
dim query as string
query = "Select distinct ', '+emailaddress1 "
query = query & "from contact "
would this work inside vba? My query returns too many records in excel but not in SQL?
Please just focus on this 2 lines of code and not worry about the rest of my sql call, I'm just wondering whether or not this specific string would work?
Your code will return a column where each row would be an email address with a comma in front of it. If that is what you want, then yes, it will work.
If, on contrary, you want a single string where all email addresses would be listed, separated with commas, that'd be
query = "declare #foo varchar(max);"
query = query & "select distinct #foo = isnull(#foo,'') + emailaddress1 + ', ' from contact;"
query = query & "select left(#foo, len(#foo)-2);"