I have a MS Access database that records financial transactions. It has a form named frmDeposits
that is based on table tblDep
. One of the buttons on that form runs a procedure that inserts data from the current record into another table, tblAccount
, using DoCmd.RunSql
. The code looks like this:
DoCmd.RunSQL "INSERT INTO tblAccount ([Date], CheckNo, Amount, Vendor, Cleared, Deposit, Printed, Misc) " _
& "SELECT [Date], CheckNo, Amount, Vendor, Cleared, " & ident & " AS Deposit, Printed, Misc " & _
& "FROM tblDep WHERE Form=" & formnum & ";"
The formnum
variable is set elsewhere, and identifies the current record in the form. The ident
variable is also defined elsewhere.
Somehow, in the process of debugging other parts of my code, the last line of this SQL statement was erased, leaving:
DoCmd.RunSQL "INSERT INTO tblAccount ([Date], CheckNo, Amount, Vendor, Cleared, Deposit, Printed, Misc) " _
& "SELECT [Date], CheckNo, Amount, Vendor, Cleared, " & ident & " AS Deposit, Printed, Misc"
Surprisingly, the form continued to operate correctly! This RunSQL statement was still picking up the current record from frmDeposits
and inserting it into the tblAccount table.
My question is, why does this work? I thought that SQL statements with a SELECT had to have a FROM clause. I know you can use INSERT INTO ... VALUES with no FROM to insert a single record, but even then you have to supply actual values and not field names.
One other thing I noticed: This only seems to work on code in the form's module. If I paste the SQL string into a query design and run it, or run similar code outside the form's scope, I get the 'Enter Parameter Value' popup box for each field. Is VBA pre-parsing the SQL string, and grabbing the form fields or text boxes for the parameters? Or is it defaulting the FROM to the form's RecordSource? I don't have text boxes on the form for all the fields referenced in the SQL string, although they all exist in the form's underlying table.
Btw, this is running in Access 2000. Yes, I know it's an outdated version, but that's what I have to work with.
**Edit - One added note, this behavior only shows up when using DoCmd.RunSQL. If I put the same SQL string into a db.Execute, it returns an 'Wrong number of parameters' error.