473,395 Members | 1,348 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to Create Automatic Dynamic Union Query

132 100+
Hi all once again!!!!
I have a table of upto 30-fields that supposed to be Converted to a table of 5-Columns by UnionQuery. The field names are:
Expand|Select|Wrap|Line Numbers
  1. CustomerID FirstName LastName Products1 Products2 Product3 ...Products28
  2.    1       APO       Denty     2           3        7      ... 4
  3.    2       Adezii    Neo       4           2        3      ... 0
  4.    ..      ...       ...       ..         ..         ..   ........
  5.    ..      ...       ...       ..         ..         ..   ........
  6.  
By using a Union Query I can Convert this table to five Columns which contains CustomerID, Firstname, LastName and Products as follows
Expand|Select|Wrap|Line Numbers
  1. CustomerID Firstname LastName Products Quantity
  2.      1       APO       Denty  Products1    2
  3.      1       APO       Denty  Products2    3
  4.      1       APO       Denty  Products3    7
  5.      ..      ...       ...    ..           ..    
  6.      1       APO       Denty  Products28   4
  7.      2       Adezii    Neo    Products1    4  
  8.      2       Adezii    Neo    Products2    2
  9.      2       Adezii    Neo    Products2    3
  10.      ..      ...       ...    ..           ..   
  11.      2       Adezii    Neo    Products28   0
  12.      ..      ...       ...    ..           ..   
  13.      ..      ...       ...    ..           .. 
  14.      ..      ...       ...    ..           ..     
  15.  
The problem is I have to write this Union Query Expression Manualy inorder for it to be in this formart.
I have more than 30Tables of this kind and new tables everyday.
Should there be any means of making it automatic please help!!!!!
(Note!!, FieldNames will remain constant for whaterver the convertions)
Please!!!!
Mar 31 '11 #1
1 3313
Stewart Ross
2,545 Expert Mod 2GB
Hi. What you ask cannot be achieved in a generalised form in SQL, but can be done if you use VBA code for recordset processing.

The function below can be called as many times as required to process each source table and output the results to a named destination table. For the first of the tables processed you need to call the function with its argument ClearPreviousValues set to True, to delete any previous version of the destination table. For all other calls you have this argument set False.

You would need to call this function from code on a form somewhere, say in the OnClick event of a command button.

The function returns True if the extract of products was successful, and false if not.

A typical call to the function looks like this:

Expand|Select|Wrap|Line Numbers
  1. blResult = fExtractProductQuantities("Name of First Input Table", "Name of Output Table", 4, 28, True)
  2. blResult = fExtractProductQuantities("Name of Second Input Table", "Name of Output Table", 4, 28, False)
The function itself is shown below. You would need to place it in a public code module (one which is shown in the Modules tab), or create a new module if there is no existing module you can use.


Expand|Select|Wrap|Line Numbers
  1. Public Function fExtractProductQuantities(ByVal SourceTableName As String, _
  2.                                           ByVal DestinationTableName As String, _
  3.                                           ByVal FirstProductFieldNo As Integer, _
  4.                                           ByVal NoOfProducts As Long, _
  5.                                           ByVal ClearPreviousValues As Boolean) As Boolean
  6. 'This function extracts individual product quantities from a non-normal source table and inserts
  7. 'these as individual rows into a specified destination table.
  8. '
  9. 'Although field names are noted as fixed for the application in which this function is to be used
  10. 'no assumptions about names are made. Instead, the fields are referred to by counting the left-most
  11. 'field in the source table as field 1, the next left as field 2, and the final field as fieldN where
  12. 'N is the number of columns in the source table.
  13.  
  14. 'Assumptions
  15. '1. The first field through to the field before FirstProductFieldNo are to be repeated on each row
  16. '   inserted in the destination table
  17. '2. The first field is a numeric customer ID, not a text field
  18. '3. The fields between the FirstProductNo column and the LastProductNo column contain numeric values
  19. '   representing the quantity of that product. The name of the field is the name of the product
  20. '   or if not, a synonym for it.
  21. '4. There are no fields to the right of the LastProductNo column which need to be output.
  22. '
  23. 'IN:  SourceTableName:      Name of the source table containing the repeated product rows
  24. '     DestinationTableName: Name of the destination table into which the result rows will be inserted
  25. '     FirstProductNo:       Column number of the first product field, taking the left-most field to be column 1 of the table
  26. '     NoOfProducts:         Number of product columns in sequence in each row
  27. '     ClearPreviousValues:  If this is set to True then the previous values in the destination table are deleted.
  28. '                           If False, the values are appended to those already in the table.
  29. '
  30. '     All arguments are required values which must be supplied when the function is called.
  31. '
  32. 'Out: function returns True if rows were inserted into the destination table, False if not.
  33. '
  34. 'Example source data
  35. 'CustomerID FirstName LastName Products1 Products2 Product3 ...Products28
  36. '   1       APO       Denty     2           3        7      ... 4
  37. '
  38. 'Example destination data
  39. 'CustomerID Firstname LastName Products Quantity
  40. '     1       APO       Denty  Products1    2
  41. '     1       APO       Denty  Products2    3
  42. '     ..      ...       ...    ..           ..
  43. '     1       APO       Denty  Products28   4
  44. '
  45. 'As the DAO object library is required a reference to the DAO object library must be available
  46. 'If the function does not compile select Tools, References and check that there is a tick against
  47. 'the Microsoft DAO 3.6 or similar object library.
  48.     Dim intCurrentField As Integer
  49.     Dim intFieldCount As Integer
  50.     Dim intProductCount As Integer
  51.     Dim rsSource As DAO.Recordset
  52.     Dim dbThisDB As DAO.Database
  53.     Dim strSQLCreate As String
  54.     Dim strSQLInsert As String
  55.     Set dbThisDB = CurrentDb
  56.     Set rsSource = dbThisDB.OpenRecordset(SourceTableName)
  57.     If rsSource.RecordCount > 0 Then
  58.         On Error Resume Next
  59.         If ClearPreviousValues Then
  60.             dbThisDB.Execute "DROP TABLE [" & DestinationTableName & "]"
  61.         End If
  62.         strSQLCreate = "Create Table [" & DestinationTableName & "] ("
  63.         For intFieldCount = 0 To FirstProductFieldNo - 2
  64.             strSQLCreate = strSQLCreate & rsSource.Fields(intFieldCount).Name & IIf(intFieldCount = 0, " INT ,", " VARCHAR(255), ")
  65.         Next
  66.         strSQLCreate = strSQLCreate & "Product VARCHAR(255), Quantity INT);"
  67.         dbThisDB.Execute strSQLCreate
  68.         On Error GoTo errEncountered
  69.         Do While Not rsSource.EOF
  70.             For intProductCount = 1 To NoOfProducts
  71.                 strSQLInsert = "INSERT INTO [" & DestinationTableName & "] Values (" & rsSource.Fields(0) & ", "
  72.                 For intFieldCount = 1 To FirstProductFieldNo - 2
  73.                     strSQLInsert = strSQLInsert & "'" & rsSource.Fields(intFieldCount) & "', "
  74.                 Next intFieldCount
  75.                 intCurrentField = intProductCount + FirstProductFieldNo - 2
  76.                 strSQLInsert = strSQLInsert & "'" & rsSource.Fields(intCurrentField).Name & "', "
  77.                 strSQLInsert = strSQLInsert & rsSource.Fields(intCurrentField) & ");"
  78.                 dbThisDB.Execute strSQLInsert
  79.             Next intProductCount
  80.             rsSource.MoveNext
  81.         Loop
  82.         rsSource.Close
  83.         fExtractProductQuantities = True
  84.     End If
  85.     Exit Function
  86. errEncountered:
  87.     fExtractProductQuantities = False
  88. End Function
I attach a text file export of a test run on a single table. I have also tested this with multiple table imports.

-Stewart
Attached Files
File Type: txt tbltest2.txt (3.6 KB, 458 views)
Apr 5 '11 #2

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

Similar topics

1
by: Buttercup | last post by:
I am having alot of trouble with a union query Im trying to create. The bizarre thing is I initially created this query and managed to save it as a view SELECT ID, DepartureDate, City,...
3
by: Dalan | last post by:
From reading Access 97 help text, it seems that to do what I need to do will require a Union Query. As this would be my first, I think I might require a little guidance. I have two tables with...
2
by: M Stery | last post by:
Have two base queries used for mailing labels with id,name,address,city,state,zip that are combined via a union query. One base query uses home address; the other base query uses biz address. I...
1
by: M Stery | last post by:
Using Transfer Text macro to create comma-delimited file of the results of union query. Underlying queries use \(999") "999\-9999! to format area code/phone number and work fine, but once the...
2
by: mattytee123 | last post by:
I have about 20 tables, of which I would like to do a union query and count of how many of each different code there is? The simplified verson of the table is structured like this. Code ...
3
by: NoodNutt | last post by:
G'day ppl. Can anyone assist me with the correct structure of the following in a Union Query. tblBookings.FinYear tblBookings.DepPrefPay tblBookings.IntPrefPay tblBookingsFinPrefPay
2
by: planetthoughtful | last post by:
Hi All, I'd like to place a subreport onto a report that draws its records from a UNION query. When I design the query and view the records all looks fine. However, when I put the query as...
1
by: bgreenspan | last post by:
Hi Everyone, I'm back for some more expert help. Here's what I am doing and what I tried. My database has entries with Contract Names and Expiry Dates, among other fields. I have a form...
1
by: cashotte | last post by:
Hi, Is there a way to have a union query (2 tables) in an other query then join a third table having the ability to edit records in the third table? Thanks, Stephane
2
kcdoell
by: kcdoell | last post by:
Hello: I am trying to create a union query but do not have a lot of experience. Basically I have the below tables: The Tables: Table Name = tblPrior CreditRegIDFK; Number; Foreign Key...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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
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...

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.