how to update a table using another table - sql

I have an access 2007 database with two tables main and main1 both tables have the same design and the same fields (85 fields)
I want to update one of them from the other one , is there an easy way to do that? I know I can use update query but I see in this case I have to specify each field in both tables in the query design and that is hard for 85 fields.
So what should I do in this case ?
UPDATE main
SET main.ID = [main1]![ID],
main.eng1job = [main1]![eng1job],
main.[eng1job-s] = [main1]![eng1job-s],
main.[eng1job-q] = [main1]![eng1job-q];

Using VBA
dim rs1 as Recordset
dim rs2 as Recordset
dim i as Integer
dim c as Integer
set rs1 = CurrentDb.OpenRecordset("main")
set rs2 = CurrentDb.OpenRecordset("main1", dbOpenDynaset)
c = rs1.Fields.Count - 1
Do Until rs1.EOF
rs2.AddNew
For i = 0 To c
rs2(i) = rs1(i)
Next
rs2.Update
rs1.MoveNext
Loop

Related

Can I perform SQL JOIN like operations with DAO Excel VBA Recordsets?

I have two recordsets, the first (rs1) is a query result from Access database, the other (rs2) was created by converting an array built inside VBA. The first contains a series of data, the second, some descriptions related to one of the columns of the first.
I'd like to join these two recordsets into a third, having the records from the first one, and the description fields of the second. Something similar to an INNER JOIN in a SQL query.
Is it possible in VBA? Something like a query using rs1 and rs2 as tables and the necessary query structure (SELECT xyx FROM rs1, rs2 WHERE abc)...
For the array in recordset conversation, I've found out this code and it works pretty well:
Private Function ADOCopyArrayIntoRecordset(argArray As Variant) As ADODB.Recordset
Dim rsADO As ADODB.Recordset
Dim lngR As Long
Dim lngC As Long
Set rsADO = New ADODB.Recordset
For lngC = 1 To UBound(argArray, 2)
rsADO.Fields.Append "Fld" & lngC, adVariant
Next lngC
rsADO.Open
For lngR = 1 To UBound(argArray, 1)
For lngC = 1 To UBound(argArray, 2)
rsADO.AddNew
rsADO.Fields(lngC - 1).Value = argArray(lngR, lngC)
Next lngC
rsADO.MoveNext
Next lngR
rsADO.MoveFirst
Set ADOCopyArrayIntoRecordset = rsADO
End Function

How to run a double loop in Access VBA

i'm learning Access by few days and i'm having some problems running into a double loop. I'm doing something wrong because i'm not expert with Access. It seems i'm stuck in an infinite loop (or some other error). My goal is to retrieve some data from the same table. Here's an example:
Table1
Field1 Field2
AAA 1
BBB 2
CCC 3
CCC 4
AAA 5
BBB 6
i want to retrieve all the records in field 2 where Field1= x (but not repeating the action if the same record is found)
Here's my code:
Dim strSQL as String, rs as DAO.Recordset, rs2 as Dao.Recordset, result as String
strSQL = "SELECT * FROM Table1"
strSQL2 = "SELECT DISTINCT Field1 FROM Table1"
Set rs = Currentdb.OpenRecordset(strSQL)
Set rs2 = Currentdb.OpenRecordset(strSQL2)
rs2.movefirst
While not rs2.EOF
rs.movefirst
result = ""
While not rs.EOF
If rs.Fields("Field1") = rs2.Fields("Field1") Then
result = result & rs.fields("Field2") & " "
rs.movenext
End if
Wend
rs2.movenext
Debug.print result
Wend
Set rs=Nothing
Set rs2 = Nothing
The result i want should be:
Result(first loop) = 1 5
Result(second loop) = 2 6
Result(third loop) = 3 4
EDIT:
i'm running loops because i need to generate emails with the data i found. I know how to generate emails but i'm only stacked with this loop. An example of emails should be like this:
number of emails = number of unique values in [table1].[field1] (so 3 in the before mentioned example)
for each email a list of all records in field2 that has the value-in-loop in field1.
Assuming Field2 actually contains unique number values, consider:
TRANSFORM Max(Table1.Field2) AS MaxOfField2
SELECT Table1.Field1
FROM Table1
GROUP BY Table1.Field1
PIVOT DCount("*","Table1","Field1='" & Field1 & "' AND Field2<" & Field2)+1;
However, if there are too many values for a CROSSTAB to handle or if you really need a single string of values from Field2 for each value in Field1, use VBA to concatenate data. One version http://allenbrowne.com/func-concat.html
Another option using the getstring method of an ado recordset.
a) Paste into a new query in sql view and save: select field1,field2list(field1) from table1
b) In a vba module, paste field2list function:
Function field2list(field1) As String
Dim rs As New adodb.Recordset
Dim ColumnSeparator
Dim RowSeparator
Dim sql
ColumnSeparator = ""
RowSeparator = ","
sql = "select field2 from table1 where field1='" & field1 & "'"
Set rs = CurrentProject.Connection.Execute(sql)
If rs.RecordCount > 0 Then
field2list = rs.GetString(, -1, ColumnSeparator, RowSeparator)
End If
End Function
c) Open query created in step a.

Using VBA and SQL, can I refer to an excel column header in a query?

I am writing a SQL query that checks excel values against a database. While running my Excel macro, I create worksheet 2 (ws2) and need to run a query which checks if each of the values in column F = table.number.
I know I can use Cells to get a single value and wrap it in a for loop but that takes up too much processing and requires too many SQL extracts. The column in ws2 is called "REFERENCE" and has all the data below it. Ideally, I would like to write the SQL query like:
select * from table where ws2.REFERENCE = table.number
Is there a way to do this?
I suppose you can do the comparison in either Excel or in SQL Server, right. I think one viable solution is to import data from SQ Server, including field names, and do compare this to what you already have in Excel.
Sub Conn2SQL()
Dim cnn1 As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim iCols As Integer
Set cnn1 = New ADODB.Connection
cnn1.ConnectionString = "driver={SQL Server};server=MyDBServer;uid=MyuserID;pwd=mypassword;database=MyDB"
cnn1.ConnectionTimeout = 30
cnn1.Open
SQry = "use MyDB select * from TableName"
mrs.Open SQry, cnn1
For iCols = 0 To mrs.Fields.Count - 1
Worksheets("Sheet2").Cells(1, iCols + 1).Value = mrs.Fields(iCols).Name
Next
Sheet2.Range("A2").CopyFromRecordset mrs
mrs.Close
cnn1.Close
End Sub

Access - Change fields in table automatically, if a field changes

Lets say I got a table with an id, pre- and lastname. I made them work as comboboxes in the table. Now if I change 1 field (lets say the id) with the combobox I want that all the other stuff is changed too (the pre and lastname). How to achieve that (with a macro or vba, or is it easier)?
I solved it. I made a sub formular. Then i managed to dropdown the fields I wanted to. Copying the same table for finding the names ids...
And then i created an event for after update:
Private Sub PartnerIdServiceWorker_AfterUpdate()
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("SELECT * FROM HTB WHERE PartnerIdServiceWorker = " & PartnerIdServiceWorker)
Do While Not rst.EOF
Me.AnredeMitarbeiter = rst!AnredeMitarbeiter
Me.VornameMitarbeiter = rst!VornameMitarbeiter
Me.NachnameMitarbeiter = rst!NachnameMitarbeiter
Exit Do
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Now I'm able to change the fields in the table and the other values do also change.

Access 2007 VBA code returns only the first record of the loop

I have two tables, I am trying to get data from table B into table A. If The ID for table A is not found in table B then leave it null.
Eg.
AID Sttl BID Sttl
4 88 3
20 92 2
88 3 100 8
92 2 500 10
800
The code I currently have only return the first similar record in table A. It does not return the next matching record (eg. it returns 3 for AID 88 but does not return anything for AID92). What am i missing?
Dim db As dao.Database
Dim rs1 As dao.Recordset
Dim rs2 As dao.Recordset
Set db = CurrentDb()
Set rst1 = db.OpenRecordset(cstrFromtbl, dbOpenDynaset)
Set rst2 = db.OpenRecordset(cstrTotbl, dbOpenDynaset)
Do While Not rs2.EOF
If rs2.Fields("A.ID") = rs1.Fields("B.ID") Then
rs2.Edit
rs2.Fields("Sttl") = rs1.Fields("Sttl")
rs2.Update
Else
rs2.Edit
rs2.Fields("Sttl") = Null
rs2.Update
End If
rs2.MoveNext
Loop
Set rs1 = Nothing
Set rs2 = Nothing
Set dbs = Nothing
End Function
I could be wrong but it looks like you are recreating SQL in VBA. The SQL below is simpler and will probably run much, much faster.
UPDATE tablea
INNER JOIN tableb
ON tablea.idfield = tableb.idfield
SET tablea.destinationfield = tableb.sourcefield
What many forgot, you can't be sure about the order of a table except you sort it. Therfore you have to do a search, and check if something was found.
Do While Not rs2.EOF
rs1.FindFirst("ID=" & rs2.Fields("A.ID"))
rs2.Edit
If rs1.NoMatch Then
rs2.Fields("Sttl") = Null
Else
rs2.Fields("Sttl") = rs1.Fields("Sttl")
EndIF
rs2.Update
rs2.MoveNext
Loop