Viewing SQL in an access database? - sql

I have an access database which has some sql queries loaded into it. I have no experience with microsoft access and need to know how I can see the sql queries it contains. My guess is they are somewhere in r_[sql name]?
What I mean specifically is to see the query itself, for example there is a form which generates an output based on various tables, my guess is there is an SQL query (like Select * from table;) doing this and I'd like to know how I can see it

You should also note that objects in Access that return recordsets (forms, reports, combo boxes, listboxes) can also have SQL properties. These cannot be seen except by examining the objects themselves (recordsource for forms/reports, rowsource for combo boxes/listboxes). So, just looking at the SQL of the stored QueryDefs is not going to show you all the SQL statements used in the app.
Additionally, if there's VBA code, there could also be SQL embedded in the code.

For each individual query, you can go to the 'View SQL', either using the button or choosing the menu option. (I only have a German access, but it should be something like View - View SQL or so).

It you are refering to view the query names and defs from VBA, the you can try
Private Sub Command0_Click()
Dim qd As queryDef
Dim queryName As String
Dim queryText As String
For Each qd In CurrentDb.QueryDefs
queryName = qd.Name
queryText = qd.SQL
Next qd
End Sub

Related

MS Access keeps on breaking my queries

I wrote a query in MS Access which I was able to run successfully. However whenever I head back to Design View in MS Access 2010, it kindly corrects it for me into SQL that doesn't even work!
Here is my original SQL (which I ran successfully):
SELECT [AssetTypeCounts].DELIVERED_IDENTIFIER,
[AssetTypeCounts].DELIVERED_SOURCE,
Switch([AssetTypeCounts].TYPES<1,"Missing",
[AssetTypeCounts].TYPES=1,"Correct",[AssetTypeCounts].TYPES>1,"Conflicting") AS STATUS
FROM (
SELECT DELIVERED_IDENTIFIER, DELIVERED_SOURCE, Sum(IIf(Len(PRODUCTTYPE)>0,1,0)) AS TYPES
FROM (
SELECT DISTINCT DELIVERED_IDENTIFIER, PRODUCTTYPE, BILLINGCODE, DELIVERED_SOURCE
FROM AprilUsageFile) AS "DisctinctAssetIdBySource"
GROUP BY DELIVERED_IDENTIFIER, DELIVERED_SOURCE
) AS AssetTypeCounts;
After I go back to Design View I get an error:
The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.
I didn't even get a chance to edit the query.
Why does Access keep changing my query?
Can I disable features where MS Access is changing my queries?
try to create a new query by printing in immediate window:
Dim qDef As DAO.QueryDef
Set qDef = CurrentDb.QueryDefs("NameOfBrokenQuery")
Debug.Print qDef.SQL
As a general rule never open SQL queries in designer mode, because access will always change parts of it and then it will be harder for your to change it.

Edit Current Object's SQL in MS Access through VBA

I am using MS Access 2013 trying to edit the SQL of the current query that is being displayed on the screen. I can get the name of the current query using qName = Application.CurrentObjectName however the current query is not saved, nor do I want it to be saved.
I know that using something like below, I can get the SQL of a saved query and modify that query.
Dim qd As QueryDef
Set qd = CurrentDb.QueryDefs(qName)
qd.SQL = "Select Customers.ID From Customers"
However, the query that I want to modify is not saved, but rather just being worked on. What I want to do is access the SQL which is visible in SQL view, read that into a variable, and modify it. I am not sure how to proceed and would appreciate some help. (What I have tried is summarized above.)
(In case you are curious. The queries I am working on may be new or may be being modified from saved queries; saving could overwrite something which I am not yet finished with/is not working, thus causing more issues.)
If your unsaved new query is open in Datasheet View, you can retrieve its SQL like this:
MsgBox Application.Screen.ActiveDatasheet.RecordSource
However if you want to modify that SQL within its current query window, I can't help you.

query criteria based on form field

So I have a query where I select a field and set the criteria so that it only selects records based on the current value of a particular field in my form. The criteria looks like this.
[Forms]![FORMAL_CERT_REVIEW_CHECK_FORM]![REVIEW_CHECK_ID]
Pretty simple stuff. But I am running into the issue where when I run the query I get the prompt that says I need to enter a value. I know that this usually happens when you set the criteria to something that may not exist or you spelt it incorrectly, but I have checked all of this and it seems like everything looks fine.
I was curious if there is something I could be missing, like a property on the field or something that I have not thought of.
When you directly open a query which includes a reference to a form control, Access is able to retrieve the query's parameter value from that control on the open form.
However, if you attempt to use the same query as the source for a recordset, Access does not resolve the query parameter from the open form.
For example, this is my query, qryREVIEW_CHECK_ID.
SELECT f.id, f.datetime_field, f.some_text
FROM tblFoo AS f
WHERE f.id=[Forms]![FORMAL_CERT_REVIEW_CHECK_FORM]![REVIEW_CHECK_ID];
With FORMAL_CERT_REVIEW_CHECK_FORM open, everything works fine when I open the form directly ... like this for example ...
DoCmd.OpenQuery "qryREVIEW_CHECK_ID"
However, using that query as the source for a recordset triggers error 3061, "Too few parameters. Expected 1."
Dim db As DAO.database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("qryREVIEW_CHECK_ID")
The workaround is to open the recordset from the QueryDef object. And include Eval() so that Access will resolve the parameter using the parameter's name.
Dim qdf As DAO.QueryDef
Set qdf = db.QueryDefs("qryREVIEW_CHECK_ID")
qdf.Parameters(0) = Eval(qdf.Parameters(0).Name)
Set rs = qdf.OpenRecordset
Your description doesn't specify whether your form is a simple form or a sub-form. I came across the same issue and realized that I was only entering the sub-form's name in the criteria.
Assuming that you have FORMAL_CERT_REVIEW_CHECK_FORM sub-form under PARENT_FORM, your criteria should read
[Forms]![PARENT_FORM]![FORMAL_CERT_REVIEW_CHECK_FORM]![REVIEW_CHECK_ID]
I hope this helps you or others. Used in Access 2016.
I have experienced this on several occasions after making a design change to the form. There is no fault with what you have done - it is an access corruption. The solution is to copy the database to another file name, delete your forma and query, compact and repair, and then import the form and query again. This normally solves the problem. It appears importing it resets the internal references allowing the form to work as it should.
Doesn't seem like this was ever solved, and I just came up with the same issue. I solved it by deleting the form and recreating it. Like you I had, [Forms]![MyForm]![ID] and out of no where it started asking for user input for the criteria on my listbox query. Making a new form and copying over the fields seems to have fixed it.

Extract the SQL Command from a database VB 2010

This may be a very strange question but I am trying to 'obtain' the SQL command for the purpose of reporting.
So say my Microsoft Access Database has a query which when executed, runs this SQL statement:
SELECT Staff.SurName, Staff.ID, Staff.Salary, Staff.StartDate, Staff.JobTitle,
Manager.SurName AS [Manager Surname], Department.DeptName AS [Department Name]
FROM Employee AS Staff, Employee AS Manager, Department
WHERE (((Staff.ManagerID)=[Manager].[ID]) AND
((Staff.DeptID)=[Department].[DeptID]));
I would like my visual Basic application to be able to 'obtain' the SQL statement for ANY given database, provided there is a statement to be obtained(I.e. If the database has any queries, obtain the statement and return it to the application), if the database has no queries, inform the user with a message.
Is this actually possible?
UPDATE:
I am trying to complete this by using the 'GetSchema()' function:
Dim schema As DataTable = con.GetSchema("PROCEDURES")
But the "PROCEDURES" is causing an error, is anyone familiar with the GetSchema() function?
I've tried all sorts in my searching efforts but I've not had any luck, so I came here.
Thanks in advance
each query has an .SQL property.
This code will loop through the current db, and give you the SQL for every query it finds:
Dim db As Database
Dim qr As QueryDef
Set db = CurrentDb
For Each qr In db.QueryDefs
MsgBox qr.SQL
Next
Assuming you have a textbox, TextBox1, and a command button named Command2, you might use:
Private Sub Command2_Click()
Me.TextBox1 = CurrentDB.QueryDefs("qryScores").Sql
End Sub

MS Access query with dynamic from statements

Ok this is vexing me. I have a query I created with an in statement in the from clause. What I am looking to do is have a global variable populate that from statement. Example
Select *
Form query1 in <Global Variable filename>
What is going on is I link to a file that has hundreds of linked table and queries in it. My database only has a few select queries and link table to different database. I did not want to re-build all the queries and linked table is my database. The issue is the file with all the links changes name once a month. I just want to read a text file with the current name of the database in it so I do not have to keep changing my queries every time the database name changes. Also this has to a query since I have other queries using the externally linked query.
I have one suggestion, but its pretty kludgy.
Rewrite the query on the fly with VBA call
Private Sub update_qtest()
Dim db As Database
Dim qd As QueryDef
Set db = CurrentDb
Set qd = db.QueryDefs("qtest")
qd.SQL = "SELECT * from query1 in " & g_file_name
End Sub
As I said, it's kludgy, but I don't think there's a way to pass the from clause as a parameter.
Another way to do this would be to just use the same file name each month so you wouldn't have to change anything in your Access app at all. You could easily code copying the file to the standard name over top of the previous copy (you'd have to delete it before copying, of course), which would retain the history.