Run MSAccess pass through query thats runs SQL stored proc asynchronously - sql

As title says trying to run pass through query asynchrnously.
I have tried
db.Execute "QrySSRSOneParameter", dbRunAsync
but this doesnt work.
So I found this code that passes the SQL statement through.
I run the following code but a get a
Could not find stored procedure 'sptest'.
It does exist.
Set ws = DBEngine.CreateWorkspace("ODBCWorkspace", "LESTERASSOCIATE\Malcolm", "access", dbUseODBC)
Set myconn = ws.OpenConnection("TestConnection", dbRunAsync, False, connstring)
Set myqry = myconn.CreateQueryDef("", "EXECUTE sptest")
myconn.Execute "EXECUTE sptest", dbRunAsync
Set myconn = Nothing
Set ws = Nothing

just looking at this code briefly and one thing struck me.
you're setting your connection then creating a query def... then not using the query def
shouldn't the execute line read
myqry.execute(dbRunAsync)

Related

Access: "Too few parameters."

I know this is a redundant question but could not find a similar scenario to mine.
I have a stored query which, when executed, picks values from the filters on an opened form and display results. All works.
Here is how the query is called:
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "qry"
Dim rsReport As New ADODB.Recordset
rsReport.CursorType = adOpenKeyset
rsReport.CursorLocation = adUseClient
rsReport.Open cmd
I am trying to use the same query from VBA to create Excel files which can be downloaded or emailed and I am getting a "Too few parameters" error now (while the form is still open). Can anyone set me in the right direction why this is happening please?
When executing a query using VBA, you can't reference open forms. You need to explicitly state all parameters.
If you're executing the query using DoCmd.RunQuery, you can set parameters using DoCmd.SetParameter.
If you're executing the query using QueryDef.Execute, you can set parameters using the QueryDef.Parameters collection.
If you're executing the query using an ADODB.Command, you can set parameters by appending parameters to the Command.Parameters collection, in the following way:
Command.Parameters.Append Command.CreateParameter ("MyParameterName", adInteger, adParamInput) where adInteger is the type. After that, you still need to set the parameter to a value by setting Command.Parameters("MyParameterName").Value = MyValue
Also see this question for info on ADODB parameters. They are a bit more tricky.
All parameters need to be filled in before executing the query.

VBA Call to SQL Stored Procedure Causing Other Pages to hang

I've got a simple piece of code that executes a SQL Server backup.
With sCmd
.ActiveConnection = sCN
.CommandText = "dbo.csp_ad_hoc_single_full_backup"
.CommandType = adCmdStoredProc
.Parameters.Refresh
.Parameters("#database_name").Value = strDB
.Parameters("#backup_dir").Value = preBackup_directory
.Parameters("#backup_dir_space").Value = objDiskSpace
.Execute , , adAsyncExecute
End With
returnvalue = sCmd.parameters(0)
This code executes when the user hits the page, the return value then displays a different text per each possible result of the procedure.
The problem is that I cannot hit any other pages while this procedure runs. I've tried using 'adAsyncExecute', but that does not seem to work. The page that displays the results and runs this code does not load until the entire backup completes. I wonder if perhaps this is why other pages hang.
Any ideas?
As per enderland's comment, VBA will not continue until the .Execute process completes.
My solution is to simply write the parameters sql table instead of immediately trying to execute the procedure. The web page will display the table write as sucessful. A job will then pick up those parameters and execute the code as it would have upon page load originally. The user will be notified of the job's completion via email using msdb.dbo.sp_send_dbmail a the end of the job.

How Do I Return Multiple Recordsets from SQL Stored Procedure in Access 2010

I’ve created a pass-through query in Access which executes a stored procedure that searches for a string across all tables in my SQL database. The stored procedure on the SQL server runs as expected, returning multiple Recordsets that contain the value of my search string. However, when I double-click on the pass-through query in Access, in Datasheet View I see the results of only one Recordset. Since it appears that Access is not designed to handle multiple result sets, then how do I use VBA in Access to accomplish this?
exec sqlsp_searchalltables #Tablenames='', #SearchStr='%motion%'
I'm not quite sure how you expected to "bind" your form to the multiple recordsets returned by the stored procedure, but as far as I know the only way to deal with SQL Server stored procedures that return multiple recordsets is to use ADODB.Recordset objects.
(Don't be misled by the "Recordset.NextRecordset Method (DAO)" article here. If you try that approach you will receive run-time error '3847': "ODBCDirect is no longer supported. Rewrite the code to use ADO instead of DAO.")
For example, I have a SQL Server stored procedure that returns two recordsets and I create a pass-through named [dbo_myMultiRsSp_1] to call it:
EXEC dbo.myMultiRsSp #id=1
If I open it in Datasheet View by double-clicking it I see the results of the first recordset.
If I want to process all of the recordsets in VBA I cannot use the pass-through query directly, but I can use its .Connect and .SQL properties as follows
Option Compare Database
Option Explicit
Sub MultiRsSpTest()
Dim cdb As DAO.Database
Dim con As ADODB.Connection, cmd As ADODB.Command
Dim r1 As ADODB.Recordset, r2 As ADODB.Recordset
Set cdb = CurrentDb
Set con = New ADODB.Connection
' connect directly to the SQL Server
' (by using the .Connect property of the pass-through query)
con.Open Mid(cdb.QueryDefs("dbo_myMultiRsSp_1").Connect, 5) ' omit "ODBC:" prefix
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandType = adCmdText
cmd.CommandText = cdb.QueryDefs("dbo_myMultiRsSp_1").SQL
Set r1 = cmd.Execute
Debug.Print
Debug.Print "First Recordset:"
Do Until r1.EOF
Debug.Print r1(0).Value
r1.MoveNext
Loop
Set r2 = r1.NextRecordset
Debug.Print
Debug.Print "Second Recordset:"
Do Until r2.EOF
Debug.Print r2(0).Value
r2.MoveNext
Loop
' r1.Close (happens implicitly)
Set r1 = Nothing
r2.Close
Set r2 = Nothing
Set cmd = Nothing
Set con = Nothing
Set cdb = Nothing
End Sub

Forcing ignoring errors from ADODB to Excel VBA

I don't know if this is possible, but I figured I'd ask.
Is there an equivalent to On Error GoTo Next for ADODB connections in Excel VBA?
I have a stored procedure I'm calling using an ADODB.Command object. The problem is, if any one statement in that stored procedure throws an error, the entire process gets shut down. Yes, that's appropriate in some cases, but in my case, it's not a big deal, I'd just like it to continue executing the rest of the stored procedure anyway.
On Error GoTo 0 shows the SQL error message and gives options to "End" or "Debug".
On Error Resume Next skips the SQL error message, but silently cancels the SQL command and moves the next VBA statement.
Any ideas?
EDIT: I've had a request for my code. I'm not sure it will help you much, but here:
On Error GoTo 0
ServerConnection.Open "Provider=MSDASQL.1;Persist Security Info=True;Extended Properties="DRIVER=SQL Native Client;Trusted_Connection=Yes;SERVER=DBServer;DATABASE=Database";"
Dim SqlCommand As ADODB.Command
Set SqlCommand = New ADODB.Command
With SqlCommand
.ActiveConnection = ServerConnection
.CommandText = "EXEC CacheTables #CacheTableType1=True"
.CommandType = adCmdText
.Execute
End With
ServerConnection.Close
Set SqlCommand = Nothing
Set ServerConnection = Nothing
I don't really control the stored procedure, unfortunately, but the reason it's throwing errors is that the person who wrote it used RAISERROR statements to tell the user where the execution is up to. This is fine in SQL Server, which understands the "Priority" flag and hence continues executing, but VBA appears to consider all errors to be the same importance.
Because the processing of your stored procedure is all taking place on your DB server, you would have to have some kind of error handling inside the stored procedure. For example a Try/Catch block in your TSQL if you are using Sql Server:
BEGIN TRY
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
[ { sql_statement | statement_block } ]
END CATCH
[ ; ]
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Alternatively you could break up your sprocs into logical divisions and surround each call with On Error GoTo Next blocks in VBA. This latter option is a pretty dirty hack though, I believe.

Stored procedure does not return data if executed from VBA

I had stored procedure MySPOld in Sybase db. I created new sp MySP. This new sp returns data while executed from Sybase Sql Advantage. But not returning the data when called from VBA - Excel 2003 (EOF property of recordset is True). Here is my code..
Dim dbCon As ADODB.Connection
Dim rstTemp As New ADODB.Recordset
Dim query As String
query = "exec MySP '01/01/2010', '01/14/2010'"
dbCon.Open connectionString, "username" "password"
dbCon.CommandTimeout = 300
rstTemp.Open query, dbCon, adOpenForwardOnly
The code was working well with old sp.
What could be the problem ? any idea ?
Thanks in Advance.
Am assuming it works ok from isql or sql advantage!
Do you compare with null anywhere in the new procedure? I've found previously that statements like "if #var = null" behave differently when called from isql etc, compared with via VBA or vbScript. If you have something like this just change it to "if #var is null" and it'll work.