The below code reads through the names of selected queries in the combo box. Then it finds the table that corresponds to that query and has to delete data from it, in order to run Insert into select query. I had Select into query, but this would delete the tables each time. Can you please help with the syntax in the docmd.Runsql ("delete * from .....) line? I need to empty the table before repopulating it with data and was therefore thinking of passing a string value with table name in the sql command. Thank you for help!
For Each valSelect In Me.Combo29.ItemsSelected
DoCmd.SetWarnings (WarningsOff)
strValue = Me.Combo29.ItemData(valSelect)
strValue3 = DLookup("TableName", "[List of Queries]", "QueryName = '" & strValue & "'")
DoCmd.RunSQL ("delete * from '& strValue3 &'")
DoCmd.OpenQuery (strValue)
Me.Combo29.Selected(valSelect) = False
Just remove the asterisk from your DELETE statement. Also, your double quotes don't look right. Might want to add some square brackets as well in case your table names have spaces in them:
DoCmd.RunSQL "delete from [" & strValue3 & "]"
could someone please have a quick look at the query i am writing below. A synopsis of what this query is suppose to be doing is to put the two characters "xx" in the field "Query04priorityselect" for all records where priority = "high". It seems that all is working other than the second to last line. The error message I get is "syntax error, missing operator" upon executing the query.
Thanks,
Private Sub Opzione61_GotFocus()
' identifies table to be updated
Dim Recordset
Set Recordset = CurrentDb.OpenRecordset("tblsearchengine01")
' puts a 1 value in the field Query04PrioritySelect for all records
Dim ClearPriority
ClearPriority = "UPDATE tblsearchengine01 SET Query04priorityselect=1"
' Run the command. / perform the update
CurrentDb.Execute ClearPriority
Dim HighPriority
HighPriority = "UPDATE tblsearchengine01 SET Query04priorityselect = ""xx"" & WHERE Priority<>high"
CurrentDb.Execute HighPriority
End Sub
I think you need to quote the word high in the WHERE clause. Single quotes are fine in Access SQL statements.
HighPriority = "UPDATE tblsearchengine01" & vbCrLf & _
"SET Query04priorityselect = 'xx' WHERE Priority <> 'high'"
Debug.Print HighPriority
CurrentDb.Execute HighPriority
If the query still throws an error, go to the Immediate window and copy the statement text which was output from Debug.Print. You can then create a new query in the Access query designer, switch it to SQL View, paste in the copied text and test that statement. Hopefully you can figure out how to fix the error. If not, copy the statement text and include it in your question.
Dim HighPriority
HighPriority = "UPDATE tblsearchengine01 SET Query04priorityselect ='xx' WHERE Priority<>high "
CurrentDb.Execute HighPriority
You don't need & between WHERE and Query04priorityselect = 'xx'
Try this
Dim HighPriority
HighPriority = "UPDATE tblsearchengine01 SET Query04priorityselect = 'xx' WHERE Priority<>'high'"
CurrentDb.Execute HighPriority
I am trying to do something like the following in a query:
Dim rs As RecordSet
Dim NewPrimaryKey as Long
Set rs = Currentdb.OpenRecordset("SELECT * FROM MyTable WHERE MyPrimaryKey Is Null;")
With rs
.AddNew
NewPrimaryKey = !MyPrimaryKey
!DateValue = Now()
...
.Update
End With
Any pointers on how to do t his using a query that I can execute in MS Access 2003 using the JET engine would be greatly appreciated.
You can use two SQL statements to accomplish what I think you want. First an INSERT. Then "SELECT ##Identity" to get the last added autonumber value. Use an object variable for the database connection with both SQL statements.
Dim db As DAO.Database
Dim NewPrimaryKey As Long
Dim strInsert As String
strInsert = "INSERT INTO MyTable ([DateValue])" & vbCrLf & _
"VALUES (Now());"
Set db = CurrentDb
db.Execute strInsert, dbFailOnError
NewPrimaryKey = db.OpenRecordset("SELECT ##Identity")(0)
Debug.Print NewPrimaryKey
Set db = Nothing
I enclosed the field name DateValue in square brackets because it is a reserved word.
Edit: If you insert multiple records with one SQL statement, SELECT ##Identity will still give you the last autonumber. It's the last autonumber for inserts performed through that connection instance. And you don't get a sequence of the autonumbers used; only the last one.
strInsert = "INSERT INTO MyTable3 ([some_text])" & vbCrLf & _
"SELECT TOP 3 foo_text FROM tblFoo" & vbCrLf & _
"WHERE foo_text Is Not Null ORDER BY foo_text;"
i am inserting values into a table
if the record exists already replace it, and if it does not exist then add a new one.
so far i have this code:
INSERT INTO table_name
VALUES (value1, value2, value3,...) where pk="some_id";
but i need something like this
if not pk="some_id" exists then INSERT INTO table_name
VALUES (value1, value2, value3,...) where pk="some_id"; else update table_name where pk="some_id"
what would be the correct SQL syntax for this?
please note that i am using sql access and that i guess it can be a combination of vba and sql
First update rows which match between your import table and master table.
UPDATE table_name AS m
INNER JOIN tblImport AS i
ON m.pk = i.pk
SET
m.field2 = i.field2,
m.field3 = i.field3,
m.field4 = i.field4;
Then add any imported records which don't exist in the master table.
INSERT INTO table_name (
pk,
field2,
field3,
field4)
SELECT
i.pk,
i.field2,
i.field3,
i.field4
FROM
tblImport AS i
LEFT JOIN table_name AS m
ON i.pk = m.pk
WHERE
(((m.pk) Is Null));
This could be done easily with recordsets. The code would then look like that (for an ADODB recordset):
myRecordset.find ....
if myRecordset.EOF then
myRecordset.addNew
endif
....
myRecordset.fields(...) = ...
....
myRecordset.update
I have posted about my approach to this problem many, many times in many different forums, but I'll just recapitulate the basic structure of the approach I use. There is no way to do it in one step, though.
update the existing records from the external data source.
insert records that don't already exist.
This assumes a common primary key that can be used to link the existing table with the external data source.
Task #2 is pretty trivial, just an outer join for the records that don't already exist.
One can use brute force for #1, writing an UPDATE statement with a SET for each field other than the primary key, but I consider that to be messy and unnecessary. Also, since I have a lot of replicated applications, I can't do that, as it would result in false conflicts (when a field is updated to the same value as it started with).
So, for that purpose, I use DAO and write an on-the-fly SQL statement to update COLUMN-BY-COLUMN. The basic structure is something like this:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim fld As DAO.Field
Dim strField As String
Dim strSet As String
Dim strWhere As String
Dim strSQL As String
Set db = CurrentDB
Set rs = db.OpenRecordset("DestinationTable")
For Each fld in rs.Fields
strField = fld.Name
If strField <> "PKField" Then
strSet = "DestinationTable." & strField & " = ExternalTable." & strField
strWhere = "Nz(DestinationTable." & strField & ",'') = Nz(ExternalTable." & strField & ", '')"
strSQL = "UPDATE DestinationTable "
strSQL = strSQL & " SET " & strSet
strSQL = strSQL & " WHERE " & strWhere
db.Execute strSQL, dbFailOnError
Debug.Print strField & ": " & db.RecordsAffected
End If
Next fld
Now, the complicated part is handling numeric vs. date vs. string fields, so you have to have some logic to write the WHERE clauses to use proper quotes and other delimiters according to the field type. Rather than test the field type, I generally just use a CASE SELECT like this, making string fields the default:
Dim strValueIfNull As String
Select Case strField
Case "DateField1", "DateField2", "NumericField2", "NumericField2", "NumericField3"
strValueIfNull = "0"
Case Else
strValueIfNull = "''"
strWhere = "Nz(DestinationTable." & strField & ", '') = Nz(ExternalTable." & strField & ", '')"
End Select
strWhere = "Nz(DestinationTable." & strField & ", " & strValueIfNull & ") = Nz(ExternalTable." & strField & ", " & strValueIfNull & ")"
I could have the details there wrong, but you get the idea, I think.
This means you'll run only as many SQL updates as there are updatable fields, and that you'll only update records that need updating. If you're also stamping your records with a "last updated" date, you'd do that in the UPDATE SQL and you'd only want to do that on the records that really had different values.
I'm using MS Access 2003 and I'm trying to execute a few queries at once using VB. When I write out the query in SQL it works fine, but when I try to do it in VB it asks me to "Enter Parameter Value" for DEPA, then DND (which are the first few letters of a two strings I have). Here's the code:
Option Compare Database
Public Sub RemoveDupelicateDepartments()
Dim oldID As String
Dim newID As String
Dim sqlStatement As String
oldID = "DND-01"
newID = "DEPA-04"
sqlStatement = "UPDATE [Clean student table] SET [HomeDepartment]=" & newID & " WHERE [HomeDepartment]=" & oldID & ";"
DoCmd.RunSQL sqlStatement & ""
End Sub
It looks to me as though it's taking in the string up to the - then nothing else. I dunno, that's why I'm asking lol. What should my code look like?
Use (') character to set start and end of value
sqlStatement = "UPDATE [Clean student
table] SET [HomeDepartment]='" & newID
& "' WHERE [HomeDepartment]='" & oldID
& "';"
You probably want to insert quotes around the IDs.