I miss some query in my database. It lost before two days and select query stays without code only select; rest there. It hit several select query in my databases. Simply when I open sql interface in Access there miss query code.
I restarted it several time but code is missing, its look really crazy from my point of view but haven't you experiences with it?
Yes, it's happened to me.
I think it's an office bug. I noticed that happens when trying to use many different nested query.
So, unfortunately, the only way to restore lost queries is... from a backup.
Try to semplificate the structure of your nested queries.
I backup all my MS ACCESS queries with a script I found, Saved me MANY times.
Dim db As Object
Dim qdf As Object
Dim ff As Long
Backup_File = gDBPATH() & "\Bin\Backup_of_All_DB_Queries-" & MonthName(Month(Now()), False) & "-" & Day(Now()) & "-" & Year(Now()) & ".txt"
Backup_File_Msg = "Backup all DB queries to: " & Backup_File & " ?"
MyMsg = MsgBox(Backup_File_Msg, 260, "Query Backup")
If MyMsg = 6 Then
Set db = CurrentDb
ff = FreeFile()
Open Backup_File For Output As #ff
For Each qdf In db.QueryDefs
Print #ff, "Query: " & qdf.Name & vbCrLf
Print #ff, "SQL: " & qdf.SQL
Print #ff, "-----------------------------------------------" & vbCrLf
Next qdf
Close #ff
Backup_File_Msg = "Completed backup of all DB queries to: " & Backup_File
MyMsg = MsgBox(Backup_File_Msg, vbOKOnly, "Query Backup")
End If
Related
I am told (and agree) that it is better to replace the SQL in an existing querydef, rather than delete and re-define the querydef each time the query needs to change. But my code only seems to work the second way. Here is the code I have that works:
Dim db As Database
Set db = CurrentDb
Dim QD As QueryDef
Dim mySql As String
mySql = ""
mySql = "TRANSFORM COUNT(tblDocs.Document) AS CountOfDocument " & _
"SELECT tblDocs.[Contractor Dept], " & _
"COUNT(tblDocs.Document) AS [Total Of Document] " & _
"FROM tblDocs " & _
"GROUP BY tblDocs.[Contractor Dept] " & _
"PIVOT tblDocs.[Engineering Status Code]"
On Error Resume Next
db.QueryDefs.Delete "qryX" 'Remove temporary query if exists
Set QD = db.CreateQueryDef("qryX", mySql) 'create temporary query
DoCmd.RunSQL "SELECT * INTO tblDocsCrossTabX FROM qryX;"
Here is the code I can't get to work
Dim db As Database
Set db = CurrentDb
Dim QD As QueryDef
Dim mySql As String
mySql = " "
Set QD = db.CreateQueryDef(("qryX"), mySql)
mySql = "TRANSFORM COUNT(tblDocs.Document) AS CountOfDocument " & _
"SELECT tblDocs.[Contractor Dept], " & _
"COUNT(tblDocs.Document) AS [Total Of Document] " & _
"FROM tblDocs " & _
"GROUP BY tblDocs.[Contractor Dept] " & _
"PIVOT tblDocs.[Engineering Status Code]"
QD.SQL = mySQL 'overwrite query SQL
DoCmd.RunSQL "SELECT * INTO tblDocsCrossTabX FROM qryX;"
Oddly, the second version doesn't throw any errors at me, but it doesn't make the crosstab table at all.
Edit: Maybe I wasn't clear enough. The problem is that the second set of code Does. Not. Execute. The. SQL. If it executed the code, I would be happy to re-write and use the same temp query over and over, but it does. not. execute. the. SQL..
Please respond with how to make the code in the second block actually execute the indicated SQL statement and build the desired table.
I know I have to remake a query if I delete it. Duh.
I know I "should" be able to re-use the same query if I can get the Set statement to properly overwrite the previous sql with the desired sql.
I know you all want to provide an answer, but please make it an answer to the question I am asking.
You can recycle the object if you don't delete it:
' On Error Resume Next
Set QD = db.QueryDefs("qryX")
QD.SQL = mySQL
DoCmd.RunSQL "SELECT * INTO tblDocsCrossTabX FROM qryX;"
Solved.
In the first block of code, when I delete and recreate the query, the string mySql contains a valid SQL statement, so Access is able to assign that SQL to the querydef when I completely recreate it with SET. Specifically,
mySql = "Transform..."
Comes Before
Set QD = db.CreateQueryDef("qryX", mySql)
In the second set of code, the string mySql contains only a space when the Set command is used, as " " is not a valid SQL Statement, the Set command won't even get executed, and the QueryDef QD never even gets created.
Specifically, the error in the second code occurs because
mySql = " " 'NOT a valid SQL Statement
comes before the attempt to create the queryDef
Set QD = db.CreateQueryDef(("qryX"), mySql) 'QD never gets created because mySql is not valid SQL
preventing the assignment of a valid SQL statement later, and so no table gets created.
If you can use a subquery, you can use a tempory QueryDef instead of bothering with checking forQueryDefalready existing or not, just combine the SELECT and the INSERT-Query to use a temporaryQueryDef
Unfortunally you can't useTransformin a subquery so this code leads toRuntime-Error 3129 Invalid SQL statement.
Sql = "SELECT * INTO tblDocsCrossTabX FROM (TRANSFORM COUNT(tblDocs.Document) AS CountOfDocument " & _
"SELECT tblDocs.[Contractor Dept], " & _
"COUNT(tblDocs.Document) AS [Total Of Document] " & _
"FROM tblDocs " & _
"GROUP BY tblDocs.[Contractor Dept] " & _
"PIVOT tblDocs.[Engineering Status Code])"
With CurrentDb.CreateQueryDef(vbNullString) 'or db.CreateQueryDef("") creates a not named and therefore temporary QueryDef
.SQL = Sql
.Execute dbFailOnError
End With
Sample of successful code.
Dim db As Database
Set db = CurrentDb
Dim QueryString As String
Dim QDDocsCross As QueryDef
Set QDDocsCross = db.CreateQueryDef("DocsCross")
QueryString = "TRANSFORM COUNT(Docs.Document) AS CountOfDocument " & _
"SELECT Docs.[Contractor Dept], " & _
"COUNT(Docs.Document) AS [Total Of Document] " & _
"FROM Docs " & _
"GROUP BY Docs.[Contractor Dept] " & _
"PIVOT Docs.[Engineering Status Code]"
QDDocsCross.SQL = QueryString
I have a database that has been working well for a couple years until this morning. When I attempt to copy the contents of a remote table into a local backend, I am presented with an err: "Error 3622 - You must use the dbSeeChanges option..."
The remote table is on a server and does have an AutoNumber attribute. The backend table is a simple readonly/static snapshot that does not care about the auto numbering datatype and is defined simply as Number - I just need the table (snapshot) to be local for performance concerns.
I added the dbSeeChanges variable without success - complains about "Too few Parameters" on the db.execute line (below).
Here are some details from my db:
Dim db As Database
dim strSQL as string
Set db = CurrentDb()
strSQL = "INSERT INTO Item " & _
"SELECT dbo_Item.* " & _
"FROM dbo_Item " & _
"WHERE dbo_Item.MASTER_INVID= " & TempVars!my_InvID
db.Execute strSQL, dbFailOnError + dbSeeChanges
What am I missing? Any suggestions to avoid/correct.
Another way to do this is to make a copy of the linked table then covert that to a local table:
localTableName = "Item"
DoCmd.CopyObject , localTableName , acTable, "dbo_Item"
DoCmd.SelectObject acTable, localTableName , True
RunCommand acCmdConvertLinkedTableToLocal
I've been given a small Access database to work on. The guy who created it wrote many custom queries to generate reports. I've been tasked with modifying the reports and the guy who initially wrote the queries is gone and left no documentation.
My biggest issue is that he nested the queries 5+ levels deep and it's incredibly difficult for me to read the way it is. The queries he wrote generally have this format but are way more complex.
SELECT thisCol, thatCol, theOtherCol
FROM CustomQuery1, CustomQuery2, CustomQuery3
And CustomQuery{1,2,3} are each written the exact same way where they reference multiple other sub-queries. Not only do I find this incredibly hard to read but I worry if I modify one of the queries that perhaps it's called elsewhere in another query that I'm not aware of that will break another report. I'm wondering if there's a way to analyze all the queries to figure out which ones are called by what other queries and/or if there's some tool out there that could automatically un-nest them or if I just have to trace through them all manually.
One thing that will help you a good deal is the Object Dependencies pane, which is built into Access. Note that you'll need to turn on Name AutoCorrect while checking that, even if you have it off the rest of the time, as is usually best. Also, it won't display VBA code references to queries, so you'll have to check those yourself by searching.
Yes, there's a way to determine if a query is used by another query. I created a form to do exactly this so that I could select multiple database objects and delete them simultaneously because I hated how Access only lets you natively delete 1 database object (i.e. form, table, etc...) at a time, and I wanted to make sure that the database objects I wanted to delete weren't referenced elsewhere.
Unfortunately, I can't upload the form anywhere from my work computer, they block that stuff. However, I can tell you that what you have to do is search through the QueryDef.SQL of each QueryDef in your database.
You're going to have to pick this apart a little, but this is the VBA I wrote to do it.
Private Sub ListObjects_Click()
' Search all queries for SQL containing the specified string.
Screen.MousePointer = 11
On Error GoTo Err_SearchQueries
Dim db As DAO.Database
Dim qdf As QueryDef
Dim varTest As Variant
Dim lngSearchCount As Long
Dim lngFoundCount As Long
Set db = CurrentDb
lngFoundCount = 0
lngSearchCount = 0
Me.txtTblSearch = "*** Beginning search for " & Me.ListObjects.Column(0) & "..." & vbCrLf
'Get a count of the database objects that will be searched
For Each qdf In db.QueryDefs
With qdf
If Left(qdf.Name, 3) = "~sq" Then
lngSearchCount = lngSearchCount + 1
End If
End With
Next qdf
For Each qd In db.QueryDefs
If InStr(1, qd.SQL, Me.ListObjects.Column(0)) > 0 Then
If Left(qd.Name, 4) = "~sq_" Then
If Mid(qd.Name, 5, 1) = "f" Then
Me.txtTblSearch = txtTblSearch & "found in Form " & Right(qd.Name, Len(qd.Name) - 5) & vbCrLf
lngFoundCount = lngFoundCount + 1
ElseIf Mid(qd.Name, 5, 1) = "r" Then
Me.txtTblSearch = txtTblSearch & "found in Report " & Right(qd.Name, Len(qd.Name) - 5) & vbCrLf
lngFoundCount = lngFoundCount + 1
ElseIf Mid(qd.Name, 5, 1) = "d" Then
Me.txtTblSearch = txtTblSearch & "found in Report " & Right(qd.Name, Len(qd.Name) - 5) & vbCrLf
lngFoundCount = lngFoundCount + 1
ElseIf Mid(qd.Name, 5, 1) = "c" Then
Me.txtTblSearch = txtTblSearch & "found in a control in Form " & Right(qd.Name, Len(qd.Name) - 5) & vbCrLf
lngFoundCount = lngFoundCount + 1
End If
Else
Me.txtTblSearch = txtTblSearch & "found in Query " & qd.Name & vbCrLf
lngFoundCount = lngFoundCount + 1
End If
End If
Next qd
Set qd = Nothing
Set db = Nothing
Exit_SearchQueries:
Set qdf = Nothing
Set db = Nothing
Me.txtTblSearch = Me.txtTblSearch & vbCrLf
Me.txtTblSearch = Me.txtTblSearch & "*** Searched " & lngSearchCount & _
" objects, found " & lngFoundCount & " occurrences."
Screen.MousePointer = 0
Exit Sub
'If an error is thrown, alert the user as to which object caused it
Err_SearchQueries:
MsgBox Err.Description, vbExclamation, "Error " & Err.Number
If IsNull(qd.Name) Then
Else
MsgBox "Possible issue with query: " & qd.Name
End If
Screen.MousePointer = 0
Resume Exit_SearchQueries
End Sub
Here's a pic of the form in action, to give you an idea:
So I have been scratching my head for awhile on this issue and although it seems simple in theory I am having a tough time implementing it in VBA.
Some background on the project will be needed to understand what i am trying to do
So our database/application is meant to keep track of how we test a version of software, what the results are, and if the tests were done properly. we have a specific set of scripts that we use from version to version.
In the database we have a table that list these scripts without assigning them to a specific version of software.
then we have a form where you select the version of software you are running against.
here is the problem i am encountering
when you have selected a software version I want to have a button that you click and it takes all the associated test scripts copies them and assigns the selected software version IF THIS HASNT BEEN DONE YET. this will allow you to make notes for the specific script that can differ from version to version.
I am currently trying to do this with a union query and have experimented with using the append query but haven had any luck, with the code snippet that i am putting below the results i get when i click the button to execute the assigning of the software version it alerts the proper "Test Script", PROC_CHECK_ID and "Software Version" but then i get a strange prompt that sais "Enter Paramater Value" and it sais the "Test Script Name" with a text field, this goes into an infite loop where i can just keep entering values in the text field.
Here is my code
Dim rs1 As DAO.Recordset
Dim unionquery As String
Dim CURRENT_SOFTWARE_VERSION As String
CURRENT_SOFTWARE_VERSION = Me.Parent.[Software Version].Value
unionquery = "select [Test Script] , [PROC_CHECK_ID], [Software Version] from (FORMAL_CERT_PROCEDURE_TEST_SCRIPTS inner join FORMAL_CERT_PROCEDURE_CHECK on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_PROCEDURE_CHECK.TEST_CASE_ID) inner join FORMAL_CERT_SOFTWARE_VERSION on FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = FORMAL_CERT_SOFTWARE_VERSION.TEST_CASE_ID where PROC_CHECK_ID=" & Me.PROC_CHECK_ID & " AND [Software Version]=""" & CURRENT_SOFTWARE_VERSION & """ "
' Debug.Print unionquery
Set rs1 = CurrentDb.OpenRecordset(unionquery, dbOpenForwardOnly)
If Not (rs1.EOF And rs1.BOF) Then
Do Until rs1.EOF = True
' MsgBox " " & rs1![Test Script] & ", " & rs1![PROC_CHECK_ID] & ", " & rs1![Software Version] & " "
INSERT_INTO_TEST_SCRIPTS = "insert into FORMAL_CERT_PROCEDURE_TEST_SCRIPTS([Test Script], [PROC_CHECK_ID_FK], [Software_Version], [TEST_CASE_ID]) values(" & rs1![Test Script] & ", " & rs1!PROC_CHECK_ID & ", " & rs1![Software Version].Value & ", " & Me.TEST_CASE_ID & ")"
' APPEND QUERY THAT THROWS INTO AN INFINITE LOOP *NEEDS WORK* INSERT_INTO_TEST_SCRIPTS = "INSERT INTO FORMAL_CERT_PROCEDURE_TEST_SCRIPTS([Test Script], [PROC_CHECK_ID_FK], [Software_Version], [TEST_CASE_ID]) SELECT FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.[Test Script], " & rs1!PROC_CHECK_ID & ", " & rs1![Software Version].Value & ", FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS WHERE FORMAL_CERT_PROCEDURE_TEST_SCRIPTS.TEST_CASE_ID = " & Me.TEST_CASE_ID & " "
DoCmd.SetWarnings False
DoCmd.RunSQL INSERT_INTO_TEST_SCRIPTS
DoCmd.SetWarnings True
rs1.MoveNext
Loop
End If
I appreciate any help and am willing to completely rework this mechanic, i am probably over complicating this : /
thanks!
Your first SELECT query (unionquery) has quotes around the value for [Software Version], indicating that it is a text field. However, your subsequent INSERT query (INSERT_INTO_TEST_SCRIPTS) omits the quotes. Therefore, the INSERT query is treating the value you are trying to insert as the name of some other field, and since no other field exists with that name you are getting the parameter prompt.
Your code might be a bit cleaner (and more reliable) if you did a Recordset insert instead of "gluing together" an INSERT statement. That approach would look something like this:
Dim rs2 As DAO.Recordset
Set rs2 = CurrentDb.OpenRecordset( _
"SELECT * FROM FORMAL_CERT_PROCEDURE_TEST_SCRIPTS", _
dbOpenDynaset)
rs2.AddNew
rs2![Test Script] = rs1![Test Script]
rs2![PROC_CHECK_ID_FK] = rs1!PROC_CHECK_ID
rs2![Software_Version] = rs1![Software Version]
rs2![TEST_CASE_ID] = Me.TEST_CASE_ID
rs2.Update
rs2.Close
Set rs2 = Nothing
I have been facing the error 3061 with error message "Too few Parameters: Expected 2". I have done all of the following to resolve the issue but still couldn't it.
I ran the query in SQL mode and it gives me result
I checked all the field names
I checked all the "&" s are placed. I find them correct.
Here is my code:
Private Sub cmbYear_Change()
Dim db As Database
Dim rs As DAO.Recordset
Dim Query As String
Query = " SELECT Yrs_Teaching, Highest_Edu, AD_Descr FROM ClassSurvey" & _
" WHERE ClassSurvey.Program/School_ID = " & Me.cmbProgId.Value & _
" AND ClassSurvey.ClassID = " & Me.cmbClassId.Value & _
" AND ClassSurvey.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND ClassSurvey.SYear = " & Me.cmbYear.Value
Set db = CurrentDb
Set rs = db.OpenRecordset(Query)
If rs.RecordCount > 0 Then
Me.TB1 = rs!Yrs_Teaching
Me.TB2 = rs!Highest_Edu
Me.TB3 = rs!AD_Descr
Else
Me.TB1 = "N/A"
End If
Set rs = Nothing
Set db = Nothing
End Sub
It appears your table includes a field named Program/School_ID. Bracket that field name in the SELECT statement so the db engine can properly recognize it as one field name.
That change might be all you need. But if you have another problem, give yourself an opportunity to examine the completed SELECT statement you're giving to the db engine. It might not be what you expect.
Dim db As Database
Dim rs As DAO.Recordset
Dim strQuery As String
strQuery = "SELECT cs.Yrs_Teaching, cs.Highest_Edu, cs.AD_Descr FROM ClassSurvey AS cs" & _
" WHERE cs.[Program/School_ID] = " & Me.cmbProgId.Value & _
" AND cs.ClassID = " & Me.cmbClassId.Value & _
" AND cs.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND cs.SYear = " & Me.cmbYear.Value
Debug.Print strQuery
Set db = CurrentDb
Set rs = db.OpenRecordset(strQuery)
If you get an error, you can go to the Immediate window (Ctrl+g), copy the statement text from there, open a new query in the query designer, switch to SQL View, paste in the statement text and try running it there. This tip is especially useful when the db engine complains about a missing parameter because when you try to run the query from the designer, Access will show you an input box asking you to supply a value and that box also contains the name of whatever Access thinks is the parameter.
I came across this when I was looking for a solution to the same problem. Turns out one of the values from a control on the form was not passing the value to the statement, sending it to the debug window (Debug.print) helped me spot the problem after a long time because I was using a global variable which the sql query was parsing. So load your controls' values into variables first!
This error may be because the column names in the query have special characters. Try surrounding the column names with square brackets in the SQL query. Column name with special symbols should be within square brackets and variables should be inside single quotes.
I had this issue too, I realized it was because I did not put quotes around my variables.
This was fixed by adding '& Chr(34)' around my variables
My fixed code looks like:
TextProducer = [Forms]![MyFormName]![TextInputBoxName]
strQuery = "SELECT FILEMASK" & _
" FROM TABLE_NAME" & _
" WHERE Producer = " & Chr(34) & TextProducer & Chr(34)