473,512 Members | 15,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing field names of two tables

65 New Member
I have spent a few hours searching for a similar Problem to mine. though there are a few replies, i could not find any to the Point.

so basically, i have two tables. one is a Standard Access table (table1) and the other is a table imported from Excel (table2). now table2 has the field names of table 1 and also a few other extra fields that i dont Need. now i want Access to compare These two tables and copy into table 1 the contents of whichever fields that it can match from table 2.

i have tried INFORMATION_SCHEMA.COLUMNS, but the code does not seem to recognise this Expression.

can anyone suggest some ideas please!!! can give more Details if required.

Thanks a lot..

saran
Feb 1 '16 #1
19 4624
NeoPa
32,557 Recognized Expert Moderator MVP
To copy data from [FromTable] into [ToTable] but only where the fieldnames match you can build up a SQL string in your code which you can then execute.

The basic template of the SQL string for an APPEND query is :
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO [FromTable]
  2.           ( [Field1]
  3.           , [Field2]
  4.           , ...
  5.           , [FieldN] )
  6. SELECT      [Field1]
  7.           , [Field2]
  8.           , ...
  9.           , [FieldN]
  10. FROM        [ToTable]
Notice that [Field1] to [FieldN] is common for both the INSERT INTO and SELECT clauses.

This part of the overall string can be built up from comparing the values of CurrentDb().TableDefs("ToTable").Fields().Name with CurrentDb().TableDefs("FromTable").Fields().Name. Where a fieldname from [ToTable] matches one from [fromTable] then it gets added to the string (with the brackets and the comma). Any that aren't in both tables are ignored.

Once the SQL string is fully and correctly formulated then execute it.
Feb 1 '16 #2
saranmc
65 New Member
Thank you for your reply @NeoPa. I formulated the append query but there is an issue.

table1 = MLE_Table
table2 = tbl_Import

now, table1 is a Standard table like a master table. table2 changes everytime the user Uploads a new file. so the Information from table 2 has to go into table1 and table1 keeps growing. now the Problem is that table2 is user uploaded and therefore it can be that sometimes a field might be missing in case of this Scenario the code must copy the other fields and leave this field blank in table1. this is where the INSERT INTO Statement does not seem to be working. if one of the fields is missing, then the whole SQL does not work.

thats why i think i Need to compare the field names everytime a new file is uploaded. please help me with this. this is the code that i am using

Expand|Select|Wrap|Line Numbers
  1. strSQL = INSERT INTO MLE_Table ( pnr, risk, reason, justification )
  2. SELECT tbl_Import.pnr, tbl_Import.risk, tbl_Import.reason, tbl_Import.justification
  3. FROM tbl_Import;
  4. DoCmd.RunSQL strSQL
Feb 2 '16 #3
NeoPa
32,557 Recognized Expert Moderator MVP
There are a couple of problems with this.
  1. The code you've posted has never compiled in VBA. It's just totally invalid. This is important.
    See Before Posting (VBA or SQL) Code. If I'm to help you at all you need to make sure you follow those instructions. I don't have time to point out all the problems the compiler can already tell you about. I will if you struggle even with what it tells you, but you must do those basics first at least.
  2. Please notice that the code I posted in my earlier offering was SQL code. This is also important.
    The instructions were to build up the string using the field names of the fields from both tables and then execute it. There is nothing in your VBA code that indicates you've understood that, so I'll try to make the process a little clearer.
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO [FromTable]
  2.           ( [Field1]
  3.           , [Field2]
  4.           , ...
  5.           , [FieldN] )
  6. SELECT      [Field1]
  7.           , [Field2]
  8.           , ...
  9.           , [FieldN]
  10. FROM        [ToTable]
That's the same SQL string, but the variable bits that need adding in the loop are underlined. Notice again that both bits are the same so only need to be worked out once even if they're added to the eventual string twice.

Here's some code that will return a string of the SQL you'll need, including all your field names. This is in the form of a function procedure so is fully portable.
Expand|Select|Wrap|Line Numbers
  1. Private Function GetAppendSQL(strFrom As String, strTo As String) As String
  2.     Dim strField As String
  3.     Dim dbVar As DAO.Database
  4.     Dim fldVar As DAO.Field
  5.     Dim flsFrom As DAO.Fields, flsTo As DAO.Fields
  6.  
  7.     Set dbVar = CurrentDb()
  8.     Set flsFrom = dbVar.TableDefs(strFrom).Fields
  9.     Set flsTo = dbVar.TableDefs(strTo).Fields
  10.     On Error Resume Next
  11.     For Each fldVar In flsFrom
  12.         'Reset each time for test
  13.         strField = ""
  14.         'This next line will fail if named field not present.
  15.         strField = flsTo(fldVar.Name).Name
  16.         If strField > "" Then _
  17.             GetAppendSQL = GetAppendSQL _
  18.                       & Replace(", [%N]%L          ", "%N", strField)
  19.     Next fldVar
  20.     If GetAppendSQL = "" Then Exit Function
  21.     GetAppendSQL = Replace("INSERT INTO [%F]%L" _
  22.                    & "          ( %N )%L" _
  23.                    & "SELECT      %N%L" _
  24.                    & "FROM        [%T]" _
  25.                    , "%N", Mid(GetAppendSQL, 3))
  26.     GetAppendSQL = Replace(GetAppendSQL, "%F", strFrom)
  27.     GetAppendSQL = Replace(GetAppendSQL, "%T", strTo)
  28.     GetAppendSQL = Replace(GetAppendSQL, "%L", vbNewLine)
  29. End Function
Feb 3 '16 #4
saranmc
65 New Member
I have made the changes according to your suggestions. here is the code.
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO [MLE_Table]
  2. 2.           ( [pnr]
  3. 3.           , [Overall Assesment]
  4. 4.           , [Tech Assesment]
  5. 5.           , [Risk]
  6. 6.           , [Justification]
  7. 7.           , [Reason]
  8. 8.           , [Comments]
  9. 9.           , [Findings]
  10. 10.          , [Remarks] )
  11. 11. SELECT     [pnr]
  12. 12.           , [Overall Assesment]
  13. 13.           , [Tech Assesment]
  14. 14.           , [Risk]
  15. 15.           , [Justification]
  16. 16.           , [Reason]
  17. 17.           , [Comments]
  18. 18.           , [Findings]
  19. 19.          , [Remarks] 
  20. 20. FROM        [tbl_Import]
  21.  
So, this will be my Append Query in the second set of codes that you sent??
I have modified that code to my variable names also. But I do not understand "%N", "%L" & "%T".
could you please tell me what exactly they stand for and should i Change them too?

Thanks a lot!!
Feb 4 '16 #5
NeoPa
32,557 Recognized Expert Moderator MVP
You've lost me. Where does that SQL come from? Is it the returned value of GetAppendSQL()? If not then I'm thoroughly confused. How was it created?

I'm happy to explain everything, but I need to understand where you are and what you already understand or explaining won't work very well.
Feb 5 '16 #6
saranmc
65 New Member
No, it is your code. Only I have replaced the field names with my field names.

I have not executed that SQL. I do not know how to. How do i build up GetAppendSQL()?

Please explain step by step. Right now I just have two tables, nothing more. No definite code.
Thanks a lot for your time.
Feb 5 '16 #7
zmbd
5,501 Recognized Expert Moderator Expert
Easiest, is to link to the excel table,
Create a simple select query against the linked table that shows only the fields of interest and use that query in the remaining application. Unless one is moving from Excel to a database, the hassle of importing the data into a table is often more than it's worth.

Next, I would attempt to do this using the simple external data import and mapping the proper fields, omitting those that are not needed, saving the import for latter use as needed. The import wizard does not do too bad a job at this; however, there's no data validation so you have to make sure that the incoming data from the excel sheet is the proper data type or the record may not import properly

finally, based on the aforementioned linked table, once again, create the select query, then convert to and append query (INSERT) within the Query editor. Switch to SQL view to get the string if needed and go from there... this is where NeoPa is at with the generalized SQL.
Feb 5 '16 #8
NeoPa
32,557 Recognized Expert Moderator MVP
Hi Saran.

Sorry for the delay responding. It's been hectic here.

My post #4 explains exactly what to do to build up your SQL. In case that's too complicated though, I also included the VBA code that both illustrates the concepts as well as successfully returning the exact SQL you need according to your explanation.

In the VBA code I used % and a letter to indicate those parts of the string that are to be replaced with a specified value. Lines #21 through #28 all use the Replace() function.

The SQL code you posted appears to be in the right format as far as I can see. Considering your line #4 of the code you posted in post #3 shows a valid way to execute a SQL string in VBA I'm not sure what more you need.
Feb 9 '16 #9
saranmc
65 New Member
Hi NeoPa, Hi zmbd,

thanks for confirming that my SQL is in the right Format.

The issue that I am having with the SQL (append query) is that incase(for eg.) table2.field2 and table2.field5 are empty then this INSERT INTO Statement does not work. It does not copy the other fields into table1. the code runs but all the fields in table1 are empty!!

Now as i understand NeoPa, i have to generate this SQL code using your #4 code. then maybe i will not have this problem. so i am going to try that.

Im a Little confused with where to use your code. should i make a new module and enter this code into a private property.? and i run it to produce the SQL in the intermediate window?

sorry for my lack of VBA Expertise. thanks a lot for the help!!

saran
Feb 9 '16 #10
saranmc
65 New Member
NeoPa could you please explain your code to generate the SQL a Little more in Detail. I am not sure where to replace my variable names in your code.

The REPLACE Statement is giving me some Trouble.

strFrom (from table) = tbl_Import
strTo (to table) = MLE_Table

my field names in strFrom are,
[pnr],[technical assesment],[risk],[reason],[justification],[comments]

my field names in strTo are the same but includes more fields of random names and also sometimes the fields in strFrom might not be present.

As i understood the places where you have used [%alphabet] are to be replaced with field names. correct?? But please help me with what appears where.

Thanks!!
Feb 9 '16 #11
NeoPa
32,557 Recognized Expert Moderator MVP
  1. Take the VBA code from post #4 and copy/paste it into a standard module in your project.
    No changes or replacements are needed to this code which should work exactly as pasted.
  2. Call the routine and execute the SQL with code like :
    Expand|Select|Wrap|Line Numbers
    1. Dim strSQL As String
    2. Dim dbCurDB As DAO.Database
    3.  
    4. Set dbCurDB = CurrentDb()
    5. strSQL = GetAppendSQL(strFrom:="tbl_Import", strTo:="MLE_Table")
    6. Call dbCurDB.Execute(strSQL, dbFailOnError)
To test it in the Immediate pane simply say :
Expand|Select|Wrap|Line Numbers
  1. Call dbCurDB.Execute(GetAppendSQL("tbl_Import","MLE_Table"), dbFailOnError)
I can't test this properly as I've typed it all from scratch so let us know if it works. If it doesn't then please explain clearly what does happen.
Feb 9 '16 #12
saranmc
65 New Member
Hi NeoPa,

I tried to execute your code, like you said i pasted the code to a new module and i called this module in my form using your second set of code.

I got an error message, on line 5 of your execute code.

Expand|Select|Wrap|Line Numbers
  1. strSQL = GetAppendSQL(strFrom:="tbl_Import", strTo:="MLE_Table")
error: "wrong number of arguments or invalid property assignment"
there is something wrong with "GetAppendSQL"
Feb 10 '16 #13
NeoPa
32,557 Recognized Expert Moderator MVP
That doesn't match the procedure I posted. Or should I say the parameters do match what I posted so I don't see how that error could occur.

Can you paste in your module that contains the GetAppendSQL() procedure please.
Feb 12 '16 #14
saranmc
65 New Member
i created a button on my form and used it to call the Private Function GetAppendSQL()

Expand|Select|Wrap|Line Numbers
  1. Private Sub Command64_Click()
  2.  
  3. Dim strSQL As String
  4. Dim dbCurDB As DAO.Database
  5.  
  6. Set dbCurDB = CurrentDb()
  7. strSQL = GetAppendSQL(strFrom:="tbl_Import",strTo:="MLE_Table")
  8.  
  9. Call dbCurDB.Execute(strSQL, dbFailOnError)
  10.  
  11. End Sub
the Private function GetAppendSQL() lies in a module. Could that be a mistake??

Thanks NeoPa!!
Feb 12 '16 #15
saranmc
65 New Member
and the module that contains my GetAppendSQL is as follows,

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2.  
  3. Private Function GetAppendSQL(strFrom As String, strTo As String) As String
  4.  
  5. Dim strField As String
  6. Dim dbvar As DAO.Database
  7. Dim fldVar As DAO.Field
  8. Dim flsFrom As DAO.Fields, flsTo As DAO.Fields
  9.  
  10. Set dbvar = CurrentDb()
  11. Set flsFrom = dbvar.TableDefs(strFrom).Fields
  12. Set flsTo = dbvar.TableDefs(strTo).Fields
  13. On Error Resume Next
  14.  
  15. For Each fldVar In flsFrom
  16.          'Reset each time for test strField = ""
  17.         'This next line will fail if named field not present.
  18.  
  19. strField = flsTo(fldVar.Name).Name
  20.         If strField > "" Then _
  21.             GetAppendSQL = GetAppendSQL _
  22.                            & Replace(", [%N]  L          ", "%N", strField)
  23.      Next fldVar
  24.     If GetAppendSQL = "" Then Exit Function
  25.     GetAppendSQL = Replace("INSERT INTO [%F]%L" _
  26.                     & "          ( %N )%L" _
  27.                     & "SELECT      %N%L" _
  28.                   & "FROM        [%T]" _
  29.                     , "%N", Mid(GetAppendSQL, 3))
  30.     GetAppendSQL = Replace(GetAppendSQL, "%F", strFrom)
  31.     GetAppendSQL = Replace(GetAppendSQL, "%T", strTo)
  32.     GetAppendSQL = Replace(GetAppendSQL, "%L", vbNewLine)
  33.  
  34.  End Function
I have not changed anything as you told me not to...
Feb 12 '16 #16
NeoPa
32,557 Recognized Expert Moderator MVP
Hi Saran.

This seems a little weird. You have it defined as Private in a module that's separate from where it's called from. I would expect that to fail completely as it won't see the code at all.

Are you seeing anything in the way of SQL come out of this at all?

If you want the code to be more general, and usable from anywhere in your project, then it needs to be defined as Public rather than Private. Another point to note in your modules is to use Option Explicit universally (See Require Variable Declaration).

If that fails then try updating your button procedure (Just temporarily.) to :
Expand|Select|Wrap|Line Numbers
  1. Private Sub Command64_Click()
  2.     Dim strSQL As String
  3.  
  4.     strSQL = GetAppendSQL(strFrom:="tbl_Import",strTo:="MLE_Table")
  5.     Call MsgBox(Prompt:=strSQL)
  6. End Sub
Run it through and then describe what you see in the message box that comes up.
Feb 14 '16 #17
saranmc
65 New Member
Hi NeoPa,

so i made the changes that you said (private to public) and Option explicit. Now the code runs but nothing happens.

and when i tried the new code you gave me. it gives a message box with the SQL as follows,
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO [MLE_Table] ([pnr], [datacode], [overallassesment], [techassesment],[risk], [reason], [justification], [comments], [findings], [remarks])
  2. SELECT ([pnr], [datacode], [overallassesment], [techassesment],[risk], [reason], [justification], [comments], [findings], [remarks] 
  3. FROM [tbl_Import]
  4.  
These are the field names of the target table (MLE_Table). the msgbox appears but the fields are not copied.

The source table(tbl_Import) does not have all the fields of MLE_Table so I Need to copy only the fields that match and leave the others blank. so the code has not checked for the matching fields. I think the FOR EACH Loop has not really worked.
Feb 15 '16 #18
NeoPa
32,557 Recognized Expert Moderator MVP
Hi Saran.

The results you've posted do not match what I would have expected from the code I posted. It should not be possible for a field that is only in one table to appear in the resultant SQL. the SQL should be formatted very differently from what you've posted. All in all, I can't match what you're posting with the code I posted so I suspect you've failed to copy and/or use the code correctly as instructed.

If you like you can post a sanitised version of your database, with both tables converted to local tables if they aren't already, and I will look at what is there and what isn't. That way I will have something reliable to work with and I'll be able to tell you exactly what's missing. It may be there's a problem with my code, but from what you've posted that seems unlikely. Send me a zipped copy and I can tell you for sure though.

NB. Only those two (local) tables should be required, as well as the code of course - any object or module that contains any of the code we've discussed.
Feb 16 '16 #19
saranmc
65 New Member
Hi NeoPa,

Thank you for your ideas, I finally managed to solve my Problem with help from some experts.

Incase anyone else has a similar Problem and for anyone who followed this post, here is the code that solved my Problem.

Expand|Select|Wrap|Line Numbers
  1. Sub import_function()
  2.  
  3. Dim qd As New DAO.QueryDef
  4. Dim dbvar As DAO.Database
  5. Dim strSQL As String
  6. Dim m As Integer
  7. Dim n As Integer
  8. Dim mystr As String
  9. Dim str As String
  10. Dim stp As String
  11. Dim rs As DAO.Recordset
  12. Dim rs1 As DAO.Recordset
  13. Set dbvar = CurrentDb()
  14. Set rs = CurrentDb.OpenRecordset("MLE_Table")
  15. Set rs1 = CurrentDb.OpenRecordset("tbl_Import")
  16.  
  17. With rs
  18. For n = 0 To .Fields.Count - 1
  19. str = CurrentDb().TableDefs("MLE_Table").Fields(n).Name
  20.     With rs1
  21.     For m = 0 To .Fields.Count - 1
  22.     stp = CurrentDb().TableDefs("tbl_Import").Fields(m).Name
  23.         If str = stp Then
  24.             mystr = mystr & stp & ", "
  25.             Exit For
  26.         End If
  27.     Next m
  28.     End With
  29. Next n
  30. .Close
  31. End With
  32.  
  33.  mystr = Left(mystr, Len(mystr) - 2)
  34.  
  35.  strSQL = " INSERT INTO MLE_Table (" & mystr & ")" & _
  36.            " SELECT tbl_Import." & Replace(mystr, ", ", ", tbl_Import.") & " FROM tbl_Import;"
  37.  
  38.  
  39.  DoCmd.RunSQL strSQL
  40.  
  41. End Sub
Thanks a lot NeoPa, I will be back if I have further Trouble with my Project.!!

Cheers!!

Saran
Feb 16 '16 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

1
1537
by: Simon Wigzell | last post by:
Does anyone have a definitive list of keywords to avoid or prohibit as field names for the tables for an ASP driven program that communicates with a SQL database? I have a website that allows...
6
1996
by: Dirk Van de moortel | last post by:
Hi, We have a database with some tables with (what I would denote as) 'referred field names'. Like this: DataTable1 with fields F1, F2, F3 DataTable2 with fields F3, F4, F5 DataTable3 with...
2
2901
by: Ralph | last post by:
I'm trying to import a range of cells from an Excel spreadsheet into a table in access. The first row contains column labels, but I cannot use those as my field names, both because of their format...
3
4285
by: Justin Clift | last post by:
Hi all, I'm creating a centralised table to keep a log of changes in other tables. In thinking about the PL/pgSQL trigger to write and attach to the monitored tables (probably a row level...
5
2593
by: EiEiO | last post by:
Hi All, I am trying to create an Import Form to "Map Fields" for importing many different tables into 1. The form I created has 2 columns of comboboxes ( A - AA) thru (J - JJ). The...
11
10273
by: Tim Hunter | last post by:
Hi I am using WinXP and Access 2003 Is it possible to store the field names of a table in an array and then loop through the array and update the table using the field names stored in the array? I...
4
22467
by: Bob | last post by:
Hi all, I've got a table that I've imported and it has junk at the top of the table, so after import I run a delete query to remove the junk lines then I'm left with the field names I want for...
4
1598
by: | last post by:
Given an XML file (dataset.writexml), here is my output (simplified for this posting): <?xml version="1.0" standalone="yes"?> <NewDataSet> <Category> <CategoryId>80</CategoryId>...
4
8852
by: dreaken667 | last post by:
I have a MySQL database containing 16 tables of data. Each table has a different number of columns and there are few common field names accross tables. I do have one master table with which I connect...
1
4660
by: jaceyk | last post by:
Is it even remotely possible to update field names to the correct field name for the same table using a data definition query? We have a utility that spits out data in an Access database for use in...
0
7153
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7371
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7432
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7517
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5676
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
1
791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
452
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.