简体   繁体   中英

Ms-Access Open a Query Sourced from SQL Server stored procedure

I have a SQL Server stored procedure which takes some parameters and returns records. The front end application is MS Access 2003. I have a form with some filter controls and an execute button.

When a user clicks the button, I want my VBA code to call the stored procedure with the provided parameters and then display the results in a grid using Docmd.OpenQuery or Docmd.OpenTable .

Currently, I'm using a pass-through query to open a recordset with the results of the stored procedure, then looping through the recordset to insert each record into a temporary table, which I then open using DoCmd.OpenTable .

This seems unnecessarily complicated. I would like to avoid the temporary table completely and simply display the records in a grid using DoCmd.OpenQuery if possible. If that is not possible, I would like to find a way to insert the records from the recordset into the temp table in a single step, instead of looping the recordset.

EDIT: I had previously tried opening the pass-through query using DoCmd.OpenQuery as suggested, but had received "Run time error 3270 - Property not found" when the DoCmd.OpenQuery line was executed. This led me to believe that opening the pass through directly was not possible. Here is a snippet of that version of my code:

sql = "EXEC dbo.rptContractorBidSummary " & IIf(frmClosedProjectWindow.Value = 1, "1", IIf(frmClosedProjectWindow.Value = 2, "2", "NULL"))
Set qdef = CurrentDb.QueryDefs("qryContractorBidSummary")
qdef.Connect = "ODBC;DRIVER=SQL Server;SERVER=" & Cconst.SERVER_NAME & ";DATABASE=" & stDatabase & ";UID=" & stUsername & ";PWD=" & stPassword
qdef.sql = sql
qdef.ODBCTimeout = 1000
qdef.ReturnsRecords = True
Set qdef = Nothing
DoCmd.OpenQuery "qryContractorBidSummary"

EDIT: I was finally able to get this approach to work. The code is fine. The problem turned out to be that I had not set the permissions on the stored procedure correctly in the back end. Thanks for the help!

You should be able to open a saved pass-through query with DoCmd.OpenQuery . If you need to specify parameter values before opening the query you could modify the .SQL property of its QueryDef object, eg, something like this (untested):

Set cdb = CurrentDb
Set qdf = cdb.QueryDefs("yourPassThroughQuery")
qdf.SQL = "EXEC yourStoredProcedure " & yourParameterValue
Set qdf = Nothing
DoCmd.OpenQuery "yourPassThroughQuery"

Why don't you just open the passthru with docmd.openquery ?? I use that regularly. You can also set the passthru as the source of a form or a report. Just before calling it you alter its .SQL to match your criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM