access form on click event create pass through que

2019-06-14 07:12发布

问题:

I have an access form with a list of numbers [1, 2, 3, 4, 5]. When a number is clicked on, i want to run a pass through query that opens a datasheet view of the query. So for example, say [3] is clicked, then a pass through query would run SQL like

select * from mytable where number=3  

Do I have to use VBA for this? How is it done in VBA? I have the log in information for the SQL server, but no permissions other than querying tables.

回答1:

You can send SQL queries to your SQL Server databases via ADO.

More on ADO: http://support.microsoft.com/kb/257819

See Also: Connecting to SQL Server over network using ADO from Excel VBA



回答2:

The easiest way to achieve what you want to do is to create and save a Query in your database which you can call DoCmd.OpenQuery on.

The most efficient way to pull the data would be a pass-through query which has the predicate (WHERE element) set already (and all the connection properties as well). The challenge here is to pass the parameter (1-5) through to the saved pass-through query in a way you can call DoCmd.OpenQuery on it.

A way to do this would be to on the AfterUpdate event of the updated control that supplies 1-5, create a pass-through QueryDef (see here: https://support.microsoft.com/kb/112108) using dynamic SQL, making sure the WHERE clause represents the number you want to filter by. You'll need to set the Connect property of the new QueryDef object to have the connection string to your external db. Save the QueryDef you create, then call it by name with DoCmd.OpenQuery. This should provide you with the functionality you are looking for.

Something you actually need to do before you create the pass-through QueryDef is check for its existence and delete it if it already exists (or update its properties, I guess) or you will get an error.



回答3:

Use a saved pass-though query and DAO.

You can do this for a total of 2 lines of code.

This code will work:

CurrentDb.QueryDefs("MyPass").SQL = "select * from mytable where number = " & Me.Number
DoCmd.OpenQuery "MyPass"