473,395 Members | 1,692 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.

Revise query's sql via code

18
Is there a way to edit queries programmatically? Most all of the table names have changed (something we had no control over). So now we have to edit each query so it's using the new tables' name. Instead of going into each query & make the changes manually, can it be done via code, as there are a lot of queries? What we need to change is if the table name doesn't start with "tbl", then it needs "dbo" placed in front of the name. I've modified queries before using the ADOX.Catalog & ADODB.Command but that's actually writing the sql in code. What I need to do is loop thru each query in the db (which I have listed in a listbox) & for each one get the sql, make the changes to the table names & then save it. We have Access 2000. We did turn the AutoCorrect on, but that didn't make changes to anything in the Criteria section.

TIA for any suggestions.
Nov 8 '08 #1
10 1851
ADezii
8,834 Expert 8TB
Is there a way to edit queries programmatically?
Yes

cpStar, you're gonna have to stay with me on this one!
  1. You will need to create 2 For...Next Nested Loops.
  2. The Outer Loop will generate all Table Names that are not prefaced with 'tbl', and are NOT System Tables, namely NOT ?Sys.
  3. The Inner Loop will retrieve all Queries that are not Temporary Objects, namely NOT ~sq*.
  4. Every qualifying Table is now cross referenced against every qualifying Query.
  5. The code now checks to see if the Table Names appear in the Query via its SQL Property and the Instr() Function.
  6. If the Table Name(s) does/do appear, its Name(s) will now be prefaced with dbo via the Replace() Function. What this does in effective is to dynamically modify the underlying SQL Statement for the Query/Queries via the SQL Property.
  7. The Algorithm is posted below. It is near my bedtime and it has not been thoroughly tested. DO NOT TEST THIS ALGORITHM ON YOUR LIVE DATABASE! I will not accept responsibility for any drastic results that may occur! All that said, here is the code, any questions, feel free to ask.
  8. Good Luck and Good Night!
Expand|Select|Wrap|Line Numbers
  1. Dim tdf As DAO.TableDef
  2. Dim qdf As DAO.QueryDef
  3.  
  4. For Each tdf In CurrentDb.TableDefs
  5.   If Left$(tdf.Name, 3) <> "tbl" And Mid$(tdf.Name, 2, 3) <> "Sys" Then
  6.     For Each qdf In CurrentDb.QueryDefs
  7.       If Left$(qdf.Name, 3) <> "~sq" Then
  8.         If InStr(qdf.SQL, tdf.Name) > 0 Then
  9.           qdf.SQL = Replace(qdf.SQL, tdf.Name, "dbo" & tdf.Name)
  10.         End If
  11.       End If
  12.     Next
  13.   End If
  14. Next
P.S. - Are you sure that you do not want the qualifying Table Names in the Queries prefaced with 'dbo.'?
Nov 9 '08 #2
cpStar
18
Hi ADezii,

That makes total sense! I work a lot with ADO, that I forget that DAO can sometimes be more helpful ... & easier to use. Thank you so much for your quick response. I'll try that today & will let you know how it goes. If you were asking if we want the tables also renamed, the answer is no as we'll be relinking them.

Thanks again for your help!
Nov 9 '08 #3
ADezii
8,834 Expert 8TB
Glad to help, let us know how you make out.
Nov 9 '08 #4
cpStar
18
Hi ADezii,

Sadly to say it didn't work. Close, but the problem is unfortunately they have named each field with the name of the table, so it's not only changing the table name but also each field's name. For ex: let's say a table is named AA then each of the fields start with AA_FName, AA_LName, etc. Someone else had set these tables up, so I have no say in that.

I'm looking into the Find Method so I can be more specific, such as whole words maybe?? I know whole words would look at AA, as in the sql referring to the joins, but do you know if it will also find AA. (AA plus period which is in sql SELECT section indicating the table then the name of the field), but will leave the field AA_LName alone? If it will, then I'm trying to figure out how to use the replace once it finds it. Any thoughts there?

Thanks again for your help!
Nov 10 '08 #5
ADezii
8,834 Expert 8TB
Don't give up so easy, you could actually:
  1. Parse each SQL Statement for each Query, namely qdf.SQL, placing each segment into an Array using the Split Function (varSQLArray = Split(qdf.SQL, " ")
  2. Check each element of the Array:
    1. If an Underscore (_) exists within the Table Name segment, leave it alone since it is actually a Field.
    2. If an Underscore (_) does not exist in the segment with the Table Name, do the normal Replace() Function appending dbo to the Table Name.
  3. Reiterate through the newly defined Array and rebuild the SQL String again.
  4. Assign the newly rebuilt String to the SQL Property of the Query, namely qdf.SQL = Top Secret Newly Rebuilt SQL String! (LOL)
  5. I'd be lying if I said that this would be simple, but if you like I'll attempt to develop the logic as long as you are in no rush.
  6. Kindly let me know one way or the other, given the unique constraints, I think your solutions are quite limited.
Nov 10 '08 #6
cpStar
18
Thanks for your quick response. I was testing something like that now ... looping thru the sql ... finding each occurrence of the table name. But then got stuck on how to replace. I came across the Mid Statement & noticed that replaces, but I don't think that will allow me to add add'l characters. I'm not familiar with the Split Function either, but will look into that as well.

I understand your logic, just not sure how to translate that into code (#2 & #3). If you have some time, that would be helpful. In the meantime, I'll check out the Split function.

Thanks again for all your time & patience on this ADezii. I really appreciate it!!
Nov 10 '08 #7
ADezii
8,834 Expert 8TB
Bit by bit, I'll see what I can come up with.
Nov 10 '08 #8
ADezii
8,834 Expert 8TB
Thanks for your quick response. I was testing something like that now ... looping thru the sql ... finding each occurrence of the table name. But then got stuck on how to replace. I came across the Mid Statement & noticed that replaces, but I don't think that will allow me to add add'l characters. I'm not familiar with the Split Function either, but will look into that as well.

I understand your logic, just not sure how to translate that into code (#2 & #3). If you have some time, that would be helpful. In the meantime, I'll check out the Split function.

Thanks again for all your time & patience on this ADezii. I really appreciate it!!
See what the following code does/does not do for you (ON A TEST DATABASE):
  1. Create the following Public Function, actually just Copy and Paste this Function into the General Declarations Section of a Standard Code Module:
    Expand|Select|Wrap|Line Numbers
    1. Public Function fReBuildSQLString(strSQL As String, strTable As String) As String
    2. On Error GoTo Err_fBuildSQLString
    3. Dim varSQLItems As Variant
    4. Dim intCounter As Integer
    5. Dim strBuildString As String
    6.  
    7. 'Parse the Components of the SQL Statement into a Variant Array using a
    8. 'Space (" ") as the Delimiter'
    9. varSQLItems = Split(strSQL, " ")
    10.  
    11. 'Interrogate all the Elements of the Array
    12. For intCounter = LBound(varSQLItems) To UBound(varSQLItems)
    13.   'Table Name not contained in the Array Element, can be SELECT, ORDER,
    14.   'Field Name, etc., rebuild SQL String
    15.   If InStr(varSQLItems(intCounter), strTable) = 0 Then
    16.     strBuildString = strBuildString & varSQLItems(intCounter) & " "
    17.   'Table Name contained in Element as well as an Underscore (-), as in
    18.   'TableName.TableName_FieldName, extract TableName_
    19.   ElseIf InStr(varSQLItems(intCounter), strTable) > 0 And InStr(varSQLItems(intCounter), "_") > 0 Then
    20.     strBuildString = strBuildString & "dbo" & Left$(varSQLItems(intCounter), _
    21.                      InStr(varSQLItems(intCounter), ".") - 1) & "." & _
    22.                      Mid$(varSQLItems(intCounter), InStr(varSQLItems(intCounter), "_") + 1) & " "
    23.     'strBuildString = strBuildString & varSQLItems(intCounter) & " "
    24.   Else      'a Table Name in the Element with no Underscore (-), preface with dbo
    25.     strBuildString = strBuildString & "dbo" & varSQLItems(intCounter) & " "
    26.   End If
    27. Next
    28.  
    29. fReBuildSQLString = Trim(strBuildString)
    30.  
    31. Exit_Err_fBuildSQLString:
    32.   Exit Function
    33.  
    34. Err_fBuildSQLString:
    35.   fReBuildSQLString = ""
    36.   Resume Exit_Err_fBuildSQLString
    37. End Function
  2. Change your Base Code to the following:
    Expand|Select|Wrap|Line Numbers
    1. Dim tdf As DAO.TableDef
    2. Dim qdf As DAO.QueryDef
    3.  
    4. For Each tdf In CurrentDb.TableDefs
    5.   If Left$(tdf.Name, 3) <> "tbl" And Mid$(tdf.Name, 2, 3) <> "Sys" Then
    6.     For Each qdf In CurrentDb.QueryDefs
    7.       If Left$(qdf.Name, 3) <> "~sq" Then
    8.         If InStr(qdf.SQL, tdf.Name) > 0 Then
    9.           'Pass the SQL Statement and Table Name to the Function fReBuildSQLString
    10.           'Debug.Print fReBuildSQLString(qdf.SQL, tdf.Name)     'Test
    11.           qdf.SQL = fReBuildSQLString(qdf.SQL, tdf.Name)
    12.         End If
    13.       End If
    14.     Next
    15.   End If
    16. Next
  3. Any questions, feel free to ask.
Nov 11 '08 #9
cpStar
18
Wow, thanks so much for all your time on this!! That’s very impressive!! Unfortunately, after all of this, I just received word, that someone tried the AutoCorrect in 2003 & evidently it changed everything, so they’re going to use that version on that computer to work on this database.

However, that said, I had already started testing what you did & just as an FYI, I noticed a couple of things. When I used the debug.print it did change the table names & left the fields alone … great job!!! But one thing I noticed in the Where clause, for some reason it put the “dbo” outside the parentheses …
ex: “ And dbo(TableName.FieldName between start date & end date) And dbo(TableName.FieldName =20)"
Also when I commented the debug.print line out & used the next line - qdf.sql = ..... – I received an error msg "Invalid sql statement - expected "Delete, Insert, Procedure, Select or Update".

Someday I hope to resolve these 2 issues as I'm sure your code works & it would be great to have on hand as you just never know when you might need something like this.

I feel terrible ADezii, after all the time you spent on this, I won't be able to use it (at least not this time), however, I do want you to know I really appreciated all your help! I learned so much!!! Thank you!!

Have a great day!!
Nov 11 '08 #10
ADezii
8,834 Expert 8TB
Not a problem, it has been a learning experience for both of us.
Nov 11 '08 #11

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

Similar topics

29
by: shank | last post by:
1) I'm getting this error: Syntax error (missing operator) in query expression on the below statement. Can I get some advice. 2) I searched ASPFAQ and came up blank. Where can find the "rules"...
3
by: Harvey | last post by:
Hi, I try to write an asp query form that lets client search any text-string and display all pages in my web server that contain the text. I have IIS 6.0 on a server 2003. The MSDN site says...
1
by: Cory | last post by:
When I run the subroutine testEmailContacts the msgbox says that there is only 1 record. The sql for qyEmailContactsQyCard is below. There is over 3000 records in the table "tbl:Contact". What am i...
0
by: starace | last post by:
I have designed a form that has 5 different list boxes where the selections within each are used as criteria in building a dynamic query. Some boxes are set for multiple selections but these list...
5
by: ????? | last post by:
I have an access query which gets data from a number of different tables. Although the tables have primary key fields, the order in which the records are returned means that none of these are in...
6
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID ...
1
by: Anan18 | last post by:
Hi there, I revised my sequence class, from the last homework to use a dynamic array to store items, i am getting an error and 4 warnings, i also provided my header file, as well as the...
11
beacon
by: beacon | last post by:
Hi everybody, I created a database that links one table from an ODBC data source. I saved my password and UID to the data source so neither myself nor anyone else would have to login each time...
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:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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
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...
0
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
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.