access 2010 bloat with forms based on pass through queries - ms-access

My access 2010 database has super massive bloat. It has gone from 44mb to 282mb in just a few runs of the VBA. Here is what I have set up:
Local tables - these calculate statistics on forms and generally don't move around too much.
Pass through queries - my personal suspect. While viewing a form, if the user clicks on a record I run a pass through query using the record the user clicked on. So user clicked on "joe", pass through query runs with sql string = "select * from sqlserver where name= " &[forms]![myform]![firstname]
After this query runs, my vba DELETES the pass through query, then recreates it after another record is selected. so the user goes back to the list of names, and clicks BRIAN. then my vba deletes the pass through query and creates another one to select all records named brian from sql server, using the same code as above.
Forms - my forms are using the pass through queries as sources.
Is what I'm doing not very smart? How can I build this better to prevent access from exploding in file size? I tried compact and repair, as well as analyze DB performance in access 2010. Any help at all is appreciated, I've been googling access2010 bloat and have read about temptables as well as closing DAO (which I am using, and which I did explicitly close). Thanks!
Here is some code for 1 of the forms i'm using -
Private Sub name_Click()
'set dims
Dim db As DAO.Database
Dim qdExtData As QueryDef
Dim strSQL As String
Dim qdf As DAO.QueryDef
'close form so it will refresh
DoCmd.Close acForm, "myform", acSaveNo
'delete old query so a new one can be created with the same name
For Each qdf In CurrentDb.QueryDefs
If qdf.Name = "QRY_PASS_THROUGH" Then
DoCmd.Close acQuery, "QRY_PASS_THROUGH", acSaveNo
DoCmd.SetWarnings False
DoCmd.DeleteObject acQuery, "QRY_PASS_THROUGH"
DoCmd.SetWarnings True
Exit For
End If
Next
Set db = CurrentDb
'sql for the data
strSQL = "select fields from (table1 inner join table2 on stuff=stuff and stuff=stuff) left join table3 on stuff=stuff and stuff=stuff where flag='P' and table.firstname = " & [Forms]![myform]![firstname]
Set qdExtData = db.CreateQueryDef("QRY_PASS_THROUGH")
'how you connect to odbc
qdExtData.Connect = "ODBC;DSN=server;UID=username;PWD=hunter2;"
qdExtData.SQL = strSQL
DoCmd.OpenForm ("names")
Forms!returns!Auto_Header0.Caption = "Names for " & Me.name & " in year " & Me.year
qdExtData.Close
db.Close
qdf.Close
Set db = Nothing
Set qdf = Nothing
End Sub

There no reason I can think of to not bind the form to a view and use the “where clause” of the open form command. It would eliminate all that code.
You could then simply use:
strWhere = "table.FirstName = '" & me.FirstName & "'"
Docmd.OpenForm "Names”,,,strWhere
Also, it makes little or no sense that a C + R does not return free space. Something else here is seriously wrong.
Also, you really don’t need to delete the query each time. Just assume that the pass-through ALWAYS exists and then use this:
strSQl = “your sql goes here as you have now”
Currentdb.Querydef("MyPass").SQL = strSQL
Docmd.Openform “your form”
The above is all you need. I count about 3 lines of code here that will replace all what you have now. Note that of course the connection string info is saved with the pass-though and does not need to be set or messed with each time.
I would also do a de-compile of your database. I have a short cut setup on all my dev machines so I can just right click to de-compile. Here is some info on de-compile:
http://www.granite.ab.ca/access/decompile.htm
So really, I don’t know why you not using the where clause of the open form? Just bind the form to a SQL view without any conditions. Then use the open form command – you only pull records down the network pipe that match your criteria.
And note how you can stuff your SQL directly into the .SQL property of the query def as above shows – again no need for that delete code and this also means you don’t mess with connection info in code either. Again about 3 lines in total.

Related

Speed Up Moving data from Oracle 11 to MySQL using MS Access

I have a little problem with downloading data from Oracle DB and moving it to the MySQL table.
On Oracle i have only a read privilege. The only task I could execute is Select.
On MySQL i have select/insert/update privilege. Also, there's no problem to change anything in mysql structure - i also have access to mysql root.
Each week I have to download huge amount of data from Oracle and move it to MySQL (for further processing). The best (and the only) solution in my case is to use MS Access.
My vba code snippet looks like (code is usually put into a loop, where I perform some inserts, each for different business site. Executing it in one query sometimes meet no end).
Public Sub DownloadData()
On Error GoTo ErrorTrans
DoCmd.SetWarnings False
Dim strWhere1 As String, strWhere2 As String, strQueryName As String
Dim qdDaneObrRabE As QueryDef, qdDaneObrRabTmp As QueryDef
Dim cnADO As ADODB.Connection
DoCmd.OpenQuery ("qryDaneObrRabCzysc") 'Calling truncate data procedure on mysql table
Set cnADO = CurrentProject.Connection
cnADO.CommandTimeout = 300 '5 minut
Set qdDaneObrRabE = CurrentDb.QueryDefs("qryDaneObrRabE")
strQueryName = "tmpObroty_" & GenerateHash(8)
Set qdDaneObrRabTmp = CurrentDb.CreateQueryDef(strQueryName, "select * from table2;") 'this select is just dummy statement, replaced some lines below
qdDaneObrRabTmp.Connect = qdDaneObrRabE.Connect
qdDaneObrRabTmp.SQL = Replace(qdDaneObrRabE.SQL, "{WHERE1}", strWhere1)
qdDaneObrRabTmp.SQL = Replace(qdDaneObrRabTmp.SQL, "{WHERE2}", strWhere2)
cnADO.Execute "INSERT INTO mysqltable SELECT * FROM " & strQueryName & ";"
Call QueryDefsCleanUp("tmpObroty_")
Call MsgBox("Success")
Set cnADO = Nothing
Exit Sub
ErrorTrans:
Call ActivityLog(Environ("USERNAME"), Now, "DownloadData", True, Err.Number, Err.Description)
End Sub
Please let me know if executing these types of inserts via ADODB is good.
I also tested DAO but i don't see difference.
All of used tables/querydefs are linked tables or pass-through querydefs.

Unable to update table through CurrentDb.Execute

Ok, before anyone tells me that it's a duplicate of another question, I don't think it's the same thing. I'm running a CurrentDb.Execute in VBA in MS Access 2007 and it's after I put the option dbFailOnError that I received this error message:
Error 3218 Could not update; currently locked
Before this, nothing was being done on the table I'm trying to update. Here's the current code in the form module:
Option Compare Database
Private Sub cmdvalidate_Click()
Dim user As String
Dim rs As Recordset
Dim strsql As String
Dim pass As String
Dim f1 As Form_frmMenu
strsql = "SELECT * FROM account WHERE username = '" & Me.txtusername & "'"
'Execute SQL and store in recordset (cannot be stored in a string or integer)
Set rs = CurrentDb.OpenRecordset(strsql)
'Go through recordset and extract first value
If rs.RecordCount > 0 Then
rs.MoveFirst
rs.Edit
pass = rs!Password
' I know it's not the best way to validate password here (since it is
' case insensitive, but it's only for internal use with 3 people in
' the same department. This will considered if there are more people
' who get involved, but for the time being, this is not important.
If pass = Me.txtpassword Then
user = rs!UserName
' MS Access debugger says the error is here
CurrentDb.Execute "UPDATE [Account] SET [Account].[Active] = 'Y' WHERE [Account].[Username] = '" & user & "'", dbFailOnError
MsgBox "Login Successful!"
'DoCmd.OpenForm "frmMenu", , , , , acDialog
Else
MsgBox "Incorrect Username Or Password. Please try again."
End If
Else
MsgBox "Something has gone wrong. Please contact your administrator."
End If
End Sub
My goal at the end of the day is to be able to get the username who logged in. I first tried to use a global variable but it seems that this is not possible with different form modules. So instead, I created the Active field so that I could get the username in other form modules through a SELECT statement.
Some checks I did:
The file is not opened by anyone besides me, I'm 100% sure of it.
The query was initially like below but I added the square brackets just in case there were reserved words:
"UPDATE Account SET Active = 'Y' WHERE Username = '" & user & "'"
Other form modules in the same file do not have this UPDATE issue and there are no other options other than Option Compare Database (the other stuff are Private Subs).
I discovered that I could use Environ("Username") to get the Windows login username in the other modules instead. This is will solve the problem, but I'm still wondering why this query cannot execute the update.
Questions:
If the table is locked, is there a way I can unlock it?
Why is this query getting an error in the first place? What has locked it?
I don't know much, if at all about vb and I'm not even sure how I got on this project...
1.) If the table is locked, is there a way I can unlock it?
I'm not so sure the entire table is locked. Perhaps only the current recordset row is locked. See #2.
2.) Why is this query getting an error in the first place? What has locked it?
The code does rs.Edit. Later, when attempting to UPDATE the table directly, the targeted row is the same row which is currently locked in the recordset. However, there is a lot more code there, which makes it difficult to pin down which statements contribute to the error.
This simplified code sample should clarify what's going on.
strSql = "SELECT * FROM account WHERE username = 'hans'"
Set rs = CurrentDb.OpenRecordset(strSql)
rs.MoveFirst
rs.Edit
CurrentDb.Execute "UPDATE Account SET Active = 'Y' WHERE Username = 'hans'", dbFailOnError
As written, that code triggers error 3218, "Could not update; currently locked", on my system.
This change disables the Edit statement and allows the UPDATE to execute successfully.
'rs.Edit
One way you found to avoid the error was by adding rs.Close before executing the UPDATE. That worked because closing the recordset released that edit lock; if you had actually changed values in that row, you would have needed rs.Update to save them before rs.Close.
However, in the original version, you were only reading values from the recordset, not changing any of them. So rs.Edit was not needed.
Huh, I think I just found out what was causing the error.
Apparently, when a RecordSet is using a table (here the line Set rs = CurrentDb.OpenRecordset(strsql)), the table can be accessed only through the RecordSet and not through CurrentDb.Execute anymore (at least, to update).
Two workarounds I found for my specific situation:
Replace the CurrentDb.Execute by something to update the RecordSet itself (Probably easier):
rs!Active = "Y" ' Change the value of Active
rs.Update ' Update the changes to the RecordSet and thus, table
rs.Close ' Close recordset
Set rs = Nothing ' Unset recordset
Close the RecordSet first, then use CurrentDb.Execute:
rs.Close
Set rs = Nothing
CurrentDb.Execute "UPDATE Account SET Active = 'Y' WHERE Username = '" & user & "'", dbFailOnError

Return multiple items in access using Dlookup

DealID is set using a Combobox and it needs to Display up to 3 MID's in the field below it
Private Sub DealID_AfterUpdate()
Dim strFilter As String
strFilter = "DealID = " & Me!DealID
Me!MID = DLookup("MID", "DealContent", strFilter)
Exit_ProductID_AfterUpdate:
Exit Sub
End Sub
That's the code I'm using the obvious limitation is Dlookup only returns the first result it finds.
That creates 2 problems but Ill focus on the first, It won't display more than one MID
so how I can get the 1-3 MIDs to be displayed?
The second issue I have is more in-depth but if anyone wants to help, a personal chat would be appreciated. Basically The form above is a child form and I need it to save a separate entry in the forms table for each Mount ID.
If anyone would like to help but doesn't understand(as is often the case with my submissions), I think screen sharing on Skype is the best option.
As already said in a comment, you can't use DLookup to return more than one value.
You need to select the first three MIDs into a Recordset, loop through them and append them to Me!MID:
Dim RS As DAO.Recordset
Dim SQL As String
'ordering is only important if you want the FIRST three MIDs.
'If you don't care, just omit the "order by MID" part.
SQL = "select top 3 MID from DealContent where DealID = xxx order by MID"
Set RS = CurrentDb.OpenRecordset(SQL)
Do While Not RS.EOF
Me!MID = Me!MID & RS("mid") & " "
RS.MoveNext
Loop
RS.Close
Set RS = Nothing
Note that this example uses DAO, which is the default (and recommended by MS) data access technology in newer Access versions. Older versions used ADO as default.
DAO works there as well, you just need a reference to Microsoft DAO x.x Object Library.

DAO.Recordset.Update results in reckord lock

I am trying to run the following code to loop around a recordset and do updates where neccessary.
I have a Microsoft Access database connected to a MySql backend. Whenever I run this code I get the following error:
3197 error: The Microsoft Office Access database engine stopped the process because you and another user are attempting to change the same data at the same time.
The code is below:
Private Sub test()
Dim rs As DAO.Recordset, rsCnt As Long, i As Long
Set rs = CurrentDb.OpenRecordset("qryMyQuery", DB_OPEN_DYNASET)
rs.MoveLast
rsCnt = rs.RecordCount
rs.MoveFirst
For i = 1 To rsCnt
rs.Edit
rs!MyFieldInTable = "test"
rs.Update
Next i
End Sub
I thought the Access database might be corrupt so I pulled an earlier backup but it's doing the same thing which makes me think it's a MySql issue.
We use an identical piece of code on another version of this database linked to a different MySql table and it works fine.
Also, when I open the query the record-set is based on I can edit the data in the query without any issues.
Just to add, on the first loop, rs!MyFieldInTable is updated, then I get the error.
It does not appear that you are moving to another record in the recordset. Simply incrementing i doesn't move to the next record. A more traditional approach would be to iterate over the recordset without the need for your other variables (i and rsCnt).
Dim rs as DAO.Recordset
Set rs = CurrentDb.OpenRecordset("qryMyQuery", DB_OPEN_DYNASET)
rs.moveFirst
Do Until rs.EOF
rs.Edit
rs!FieldNameHere = "test"
rs.Update
rs.MoveNext
Loop
EDIT
After a bit of searching I came across this thread which seems to be similar to your issue. At the bottom of the thread a suggestion is made to modify the ODBC settings for your MySQL DSN by selecting the "Advanced" tab and selecting the option to "Return Matching Rows". The post also says to drop the linked table and then re-link it to your Access database.
I haven't used Access with MySQL in the past, so I have no idea whether this will work or not, so proceed with caution!
You may also try changing your recordset to use the dbOptimistic flag for the recordset locking option to see if that helps at all:
set rs = CurrentDB.OpenRecordSet("qryMyQuery", DB_OPEN_DYNASET, dbOptimistic)
Two things you can try. First, try adding the dbSeeChanges option when opening the recordset:
Dim rs as DAO.Recordset, db As DAO.Database
Set db = Currentdb
Set rs = db.OpenRecordset("qryMyQuery", dbOpenDynaset, dbSeeChanges)
Do Until rs.EOF
rs.Edit
rs!FieldNameHere = "test"
rs.Update
rs.MoveNext
Loop
The other option, as #HansUp suggested, is to use a SQL update statement instead of a dynamic recordset. The key there is to open the recordset as a snapshot, so that changes you make to the records do not affect the recordset itself.
Dim rs as DAO.Recordset, db As DAO.Database
Set db = Currentdb
Set rs = db.OpenRecordset("qryBatchPayments", dbOpenSnapshot)
Do Until rs.EOF
db.Execute "UPDATE Payments " & _
"SET DCReference='test' " & _
"WHERE PaymentID=" & !PaymentID, dbFailOnError
rs.MoveNext
Loop
I was having the same problem and my solution turned out to be the default value for BIT(1) fields. Access does not like these to be null. Make sure you use either 0 or 1 in mysql for these fields.
I don't have MySQL here to try this against, but it looks to me as if your code is not advancing the recordset after the rs.Update method is executed, so that you are trying to udate the same field in the fierst record.
Add this line after the rs.Update:
rs.MoveNext
Hope that helps.
Try calling OpenRecordset from an object variable set to CurrentDb(), rather than directly from CurrentDb().
Dim rs as DAO.Recordset
Dim db As DAO.Database
Set db = Currentdb
Set rs = db.OpenRecordset("qryMyQuery", DB_OPEN_DYNASET)
rs.moveFirst
Do Until rs.EOF
rs.Edit
rs!FieldNameHere = "test"
rs.Update
rs.MoveNext
Loop
The reason for that suggestion is I've found operations on CurrentDb directly can throw an error about "block not set". But I don't get the error when using an object variable instead. And ISTR OpenRecordset was one such operation where this was an issue.
Also, my impression was your approach is a cumbersome way to accomplish the equivalent of:
UPDATE qryMyQuery SET FieldNameHere = "test";
However, I suspect the example is a proxy for a real world situation where the recordset approach is useful. Still that makes me wonder whether you would see the same or a different error when executing the UPDATE statement.
If you continue to have trouble with this, it may help to show us the SQL View for qryMyQuery.
I have discovered that if one tries to save data which are the same as the one already in the MySql record Access will display this kind of error. I've tried some suggestions from this thread but did not help.
The simple solution for this is to save a slightly diffrent data by using a manual time-stamp. Here is an example of heaving a sort order field and setting it to 10, 20, 30...
i = 10
timeStamp = Now()
Do Until Employee.EOF
Employee.Edit
Employee!SortOrderDefault = i
Employee!LastUpdated = timeStamp
Employee.Update
i = i + 10
Employee.MoveNext
Loop
I've tried automatic time-stamp in the MySql table but did not help when the new entry data is the same as the old one.
My little helpful hint is, bits are very, very, very bad data types to use when linking SQL tables to Microsoft Access because only SQL Server understands what a bit is, Microsoft Access has a hard time interpreting what a bit is. Change any bit datatypes to int (integers) and relink your tables that should clear things up. Also, make sure your Booleans always contain a 1 or a 0 (not a yes/no or a true/flase) in your VBA code or your updates will fail to the linked SQL tables because Microsoft Access will try to update them with a True/False or a Yes/No and SQL will not like that.
I also had same problem; i solved them adding those to code using dao.recordset:
**rst.lockedits = true**
rst.edit
rst.fields(...).value = 1 / rst!... = 1
rst.update
**rst.lockedits = false**
this seems fix conflict between just opened data (such as in a form) and updating them with code.
Sorry for my bad english... i read a lot but i never had learn it! I'm just italian.

Access: How to execute a query and save its result in a report

HI,
I am trying to write a query in vba and to save its result in a report.
I am a beginner. this is what i have tried
can somebody correct me
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
Dim sql As String
Set cn = CurrentProject.Connection
sql = "Select * from table1 where empno is 0"
rs.Open sql, cn
While Not rs.EOF
' here i think i should save the result in a report but i am not sure how
rs.MoveNext
Wend
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Also how do i change this query to run this on all tables in a database
IF you are wanting to create a report using MS Access's report generator, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort).
You can create the Query Object on the "Database" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name.
Similarly the report can be created on the "Database" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created.
Update: As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway.
The problem with this method is you would have to create a separate query and report for each table.
IF you just want to dump the result out to a text file (to read/print later), then you can do it using recordsets like you are in your VBA code. It will look something like this
'...
dim strFoo as string
dim strBar as string
'...
if not rs.bof then
rd.MoveFirst
end if
While Not rs.EOF
strFoo = rs("foo") 'copy the value in the field
'named "foo" into strFoo.
strBar = rs("bar")
'... etc. for all fields you want
'
'write out the values to a text file
'(I'll leave this an exercise for the reader)
'
rs.MoveNext
Wend
'...
Parsing all of the tables can be done in a loop something like this:
dim strTableName as string
dim db As Database
'...
Set db = CurrentDb
db.TableDefs.Refresh
For Each myTable In db.TableDefs
If Len(myTable.Connect) > 0 Then
strTableName = myTable.Name
'...
'Do something with the table
'...
End If
Next
set db = nothing
=======================UPDATE=======================
It is possible to run an MS-Access Report from a record set. To repease what I said to tksy's question
From Access Web you can use the "name" property of a recordset. You resulting code would look something like this:
In the report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
In the calling object (module, form, etc.)
Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
Q.E.D.
Normally you would design the report based on a data source. Then after your report is done and working properly you use VBA to display or save the report.
To run this for each table in the database, I'd suggest writing a function that looped through CurrentData.AllTables(i) and then called your function above in each iteration
Hope this helps
If you want to simply view the results, you can create a query. For example, here is some rough, mostly untested VBA:
Sub ViewMySQL
Dim strSQL as String
Dim strName As String
'Note that this is not sensible in that you
'will end up with as many queries open as there are tables
For Each tdf In CurrentDB.TableDefs
If Left(tdf.Name,4)<>"Msys" Then
strName = "tmp" & tdf.Name
strSQL = "Select * from [" & tdf.Name & "] where empno = 0"
UpdateQuery strName, strSQL
DoCmd.OpenQuery strName, acViewNormal
End If
Next
End Sub
Function UpdateQuery(QueryName, SQL)
If IsNull(DLookup("Name", "MsysObjects", "Name='" & QueryName & "'")) Then
CurrentDb.CreateQueryDef QueryName, SQL
Else
CurrentDb.QueryDefs(QueryName).SQL = SQL
End If
UpdateQuery = True
End Function
You may also be interested in MDB Doc, an add-in for Microsoft Access 97-2003 that allows you to document objects/properties within an Access database to an HTML file.
-- http://mdbdoc.sourceforge.net/
It's not entirely clear to me what you want to do. If you want to view the results of SQL statement, you'd create a form and set its recordsource to "Select * from table1 where empno is 0". Then you could view the results one record at a time.
If that's not what you want, then I'm afraid I just don't have enough information to answer your question.
From what you have said so far, I don't see any reason why you need VBA or a report, since you just want to view the data. A report is for printing, a form is for viewing and editing. A report is page-oriented and not that easy to navigate, while a form is record-oriented, and allows you to edit the data (if you want to).
More information about what you want to accomplish will help us give you better answers.
Had the same question. just use the clipboard!
select the query results by click/dragging over all field names shown
press ctrl-c to copy to windows clipboard
open a blank document in word and click inside it
press ctrl-v to paste from clipboard.