Access VBA dump recordset into an existing table - vba

I have a recordset and a table, both in exactly the same format. What is the syntax to dump everything in the recordset to the table? This seems to be a very simple procedure but somehow I can't find any useful information online.
Edit1: to clarify, the recordset is obtained from Table A, now I want to dump it into Table B (which is empty). Table A and B have exactly the same format.
Edit2: I am working in Access.
here is the code I used to open the recordset:
Set Table_B_rs = CurrentDb.OpenRecordset("Table_B")
I didn't make any changes to the recordset.
Thanks for the help!

You don't do this with recordsets, but with SQL by running an INSERT INTO query.
CurrentDb.Execute "INSERT INTO TableB SELECT * FROM TableA " & _
"WHERE <same conditions you used to open the recordset>"
If there is no condition, it's simply
CurrentDb.Execute "INSERT INTO Table_B SELECT * FROM Table_A"

Related

Access: Issue Creating SQL View Through VBA - Unions not allowed in subquery

First of all, let me preface this with something I almost always say in my few posts so far, which is that I'm not an IT/tech person. I'm an accountant who likes to dabble a little bit in SQL and so forth but with very minimal knowledge of VBA, so I apologize in advance if this is a super-easy question or it's already been covered. But I was not able to find anything directly related to this specific error.
Trying to use MS Access to create a view from SQL that includes a Union and getting the following error: Run-time error '-2147217900 (800040e14)': Unions not allowed in a subquery. Code is as follows:
Sub Create_View()
Dim conn As ADODB.Connection
Set conn = CurrentProject.Connection
conn.Execute "CREATE VIEW Test_VW AS SELECT A.Unit as Unit, A.Spend as Spend, A.Date as Date, A.Type as Type FROM Table1 A UNION ALL SELECT B.Unit as Unit, B.Spend as Spend, B.Date as Date, B.Type as Type FROM Table2 B;"
Application.RefreshDatabaseWindow
End Sub
This is the code as it is right now, but I've also tried UNION instead of UNION ALL, SELECT * FROM both tables as opposed to the individual columns (both tables are only the 4 listed columns, which are also the same data type), and with the columns and tables unaliased.
Something I should point out that maybe could be the issue, but I wouldn't think it is is that the "Tables" in the code are actually views that I created in Access without VBA (as in just regular SQL). These now appear as "Queries" in the database. However, I did write the VBA with the initial SQL that's defining the views, and I returned the same error. So I don't think that's the issue.
EDIT: Also, I should point out that to test, I was able to create a view from the same VBA for the top level query without the UNION.
At any rate, I'm not sure where the subquery is in the SQL, so maybe it's a syntax error?
Any help would be greatly appreciated. Thanks!
That error message, "Unions not allowed in a subquery", is not very helpful in your situation.
Access supports 2 DDL operations related to queries: CREATE VIEW; and CREATE PROCEDURE.
CREATE VIEW can be used for only simple SELECT queries. CREATE PROCEDURE must be used for more complicated SELECT queries (such as UNION) and for "action" queries.
So you could avoid your current error by using CREATE PROCEDURE instead of CREATE VIEW. However you would then encounter a different error, "The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect", due to unbracketed reserved words used as column aliases. You can drop the unneeded column aliases to avoid that error.
Here's an adaptation of your code which worked for me in Access 2010.
Dim strSql As String
strSql = "CREATE PROCEDURE Test_VW AS" & vbCrLf & _
"SELECT A.Unit, A.Spend, A.Date, A.Type FROM Table1 A" & vbCrLf & _
"UNION ALL SELECT B.Unit, B.Spend, B.Date, B.Type FROM Table2 B;"
CurrentProject.Connection.Execute strSql
QueryDefs can handle UNION. Alias field and table names are not needed.
Sub test()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("TestVW", "SELECT Unit, Spend, Date, Type FROM Table1 " & _
"UNION ALL SELECT Unit, Spend, Date, Type FROM Table2;"
Application.RefreshDatabaseWindow
End Sub
Strongly advise not to use reserved words like Date as names.

Saving a query into a Table

I have searched for a question that I am having, though I find parts of the answer I am not able to understand it fully. I am using access2010.
In simple Terms, I want to filter a table [newsearch] to show the results based on my WHERE condition.
I can use SELECT and a WHERE condition and I get a result through a query, but I want this result to be saved into [newsearch], that means I want this [newsearch] to contain only the results of this query.
I tried using SELECT INTO but since my source and destination are [newsearch], it does not work.
the query I run now is:
strSQL = "SELECT * FROM [newsearch] WHERE [newsearch].[" & Me.Combo17 & "] = '" & Me.Text18 & "'"
Set qdef = db.CreateQueryDef("User query results", strSQL)
qdef.close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
This gives me the result in a query table but I want it saved to [newsearch].
How can I do it?
select into query creates a table, but obviously you cannot create a table that already exists. You have 2 options:
Instead of selecting what you need, delete those records from your table that you do not need: delete from [newsearch] where field3<>xyz
You can use select into to create a new table, then drop [newsearch] and then rename the new table to [newsearch].

Import/Update data from Excel to SQL Server

I'm converting a database from Excel onto MS SQL server and am basically clueless.
The Excel file has column headings of GroupID, Name, Members, Remarks
The SQL table has the same fields.
When I update the SQL some records are totally new, so need to be appended, others need a column or two updated, while most records need nothing at all. So far I've taken the lazy way out & truncated the file & appended everything back in, but what's the proper way?
Import the file as a separate table and you can do all your updates from there. Depending on your version of SQL server you may be able to use the MERGE statement. It shouldn't take too long to knock up an insert, and an update statement.
Something like this for the update:
UPDATE o
SET name = i.name
FROM originaltablename o
INNER JOIN importedexceltablename i
ON o.GroupID = i.GroupID
WHERE o.name <> i.name
And something like this for the insert:
INSERT INTO originaltablename
SELECT i.*
FROM importedexceltablename i
LEFT JOIN originaltablename o
ON o.GroupID = i.GroupID
WHERE o.GroupID IS NULL
Be careful though, this is just an example to get you going as you haven't given enough information for a proper solution.

Writing to multiple columns simulatenously with SQL

I am having trouble writing a VBA macro within Microsoft Access. What I am trying to do is use SQL to create an output table, but I want to write to multiple columns simultaneously.
This gets me all the values I need for one column:
Docmd.RunSQL “INSERT INTO Output (TargetCol1) SELECT [Field1] FROM [Table1] WHERE [Criteria1] = ‘Value’ GROUP BY Field1”
When I try to run this multiple times to get the values I need for other columns. INSERT INTO writes the data as new records, so I end up with blank spaces, like this:
Field1----Field2
Value----<Null>
Value----<Null>
Value----<Null>
<Null>----Value
<Null>----Value
What I want is:
Field1----Field2
Value---- Value
Value---- Value
Value----<Null>
I tried to create variables and create kind of a nested statement but I receive a ‘Compile error, object required’ on my first line when I try to run what I have written:
Set x = Docmd.RunSQL “INSERT INTO Output (TargetCol1) SELECT [Field1] FROM [Table1] WHERE [Criteria1] = ‘Value’ GROUP BY Field1”
Set y = Docmd.RunSQL “INSERT INTO Output (TargetCol2) SELECT [Field2] FROM [Table1] WHERE [Criteria2] = ‘Value’ GROUP BY Field2”
Docmd.runsql “INSERT INTO Output (TargetCol1, TargetCol2) Values (x,y)”
Why not:
INSERT INTO Output (TargetCol1,TargetCol2) SELECT [Field1,Field2] FROM [Table1] [Criteria1] = 'Value'"
Set is used for objects, and you do not have one in Set x = Docmd.RunSQL. Order by is irrelevant for a table.
The easiest way to set up queries is using the query design window. it will guide you through creating the query and you can then switch to SQL view to get SQL.
I suggest you do not use RunSQL : What's the difference between DoCmd.SetWarnings and CurrentDB.Execute

Automatically updating/duplicating a table in Microsoft Access with VBA

Back again! So I am currently trying to programmatically have a table (Table2) update after a button is pressed. I would like for Table2 to resemble exactly another table (Table1). I'm going through this effort because Access does not allow double relationships and I have need to create one. I will therefore have two tables containing all the contact info.
I tried deleting Table2 and then creating another copy of Table1 and saving it as Table2. This would have worked is Microsoft Access didn’t throw an error because I am deleting a Table that has established relationships. So I then tried to programmatically delete and then create the appropriate relationships. However, this turns out to be a tedious exercise. A little too tedious for my taste.
My next thought is to create an append query that automatically looks for differences between the two tables and updates Table2 accordingly. The problem is that I have no idea how to structure the SQL statement for such an append query. Also is there an easier way to do this using VBA that I am missing? Thanks in advance for your help!
There is no need to go to all this trouble. You can have double relationships in MS Access. Simply add the table as many times as you need it to the relationship design window, you will get Table1, Table1_1, Table1_2 and so on, but they are all just aliases for Table1. You can now add self-joins and as many relationships as you need.
Like so:
*People*
PersonID *People_1*
ManagerID -- > PersonID
It sounds like you are able to append from Table1 to Table2 without running afoul of any relationship. If that is true, you can empty out Table2, then append all the rows from Table1.
Dim cn As Object
Set cn = CurrentProject.Connection
cn.Execute "DELETE FROM Table2"
If Table2 includes an autonumber field, reset its seed value.
cn.Execute "ALTER TABLE Table2" & vbCrLf & _
"ALTER COLUMN autonum_fld COUNTER(1, 1)"
Then do the append ...
cn.Execute _
"INSERT INTO Table2 (autonum_fld, text_field, long_int_field)" & vbCrLf & _
"SELECT autonum_fld, text_field, long_int_field" & vbCrLf & _
"FROM Table1;"
... or if the two table structures are identical, you don't even have to list the field names ...
cn.Execute "INSERT INTO Table2" & vbCrLf & _
"SELECT *" & vbCrLf & _
"FROM Table1;"
And finally ...
Set cn = Nothing
AFAICT, that could work. However, I don't understand the background details of your question, for example "Access does not allow double relationships". So I may be completely off the mark.