Execute a SQL Server stored procedure from MS Access
Asked Answered
P

2

5

I use MS Access 2013 and SQL Server 2012. I have connected my SQL Server database to MS Access. I connect to SQL Server via SQL Server Authentication. I want to execute a stored procedure with a value entered into a textbox in one of my forms. I have been trying to do it for ages now but nothing that I found on this website works for me. Can anyone please help me and give me some tips as to how to write a basic VBA code to execute the procedure? Please help!!!

Purcell answered 12/4, 2015 at 18:46 Comment(2)
Did you try creating a pass-through query using a DAO.QueryDef object?Formenti
@gord thompson No I didn't, and I have no idea how to do this...Purcell
F
5

Probably the most straightforward way is to create a temporary pass-through query using a DAO.QueryDef object. If you have an existing linked table in Access then you can use its .Connect property (ODBC connection information). All you need to do is set the .SQL property of the QueryDef to call (EXEC) the stored procedure, like this:

Option Compare Database
Option Explicit

Private Sub Command2_Click()
    Dim cdb As DAO.Database, qdf As DAO.QueryDef
    Set cdb = CurrentDb
    Set qdf = cdb.CreateQueryDef("")
    ' get .Connect property from existing ODBC linked table
    qdf.Connect = cdb.TableDefs("dbo_myContacts").Connect
    qdf.sql = "EXEC dbo.addContact N'" & Replace(Me.Text0.Value, "'", "''") & "'"
    qdf.ReturnsRecords = False
    qdf.Execute dbFailOnError
    Set qdf = Nothing
    Set cdb = Nothing
End Sub

So, for example, if the Text0 text box contains Thompson then the QueryDef will execute

EXEC dbo.addContact N'Thompson'

and if the text box contains O'Rourke then the QueryDef will execute

EXEC dbo.addContact N'O''Rourke'
Formenti answered 12/4, 2015 at 20:6 Comment(0)
S
2

After Trial and error this one worked for me

 > Private Sub UpdateItems_Click()
    >     Dim cdb As DAO.Database, qdf As DAO.QueryDef
    >     Set cdb = CurrentDb
    >     Set qdf = cdb.CreateQueryDef("")
    >     ' get .Connect property from existing ODBC linked table
    >     qdf.Connect = cdb.TableDefs("dbo_AccesLinkedTable").Connect
    >     qdf.SQL = "EXEC dbo.YourStoreProcedure"
    >     qdf.ReturnsRecords = False
    >     qdf.Execute dbFailOnError
    >     Set qdf = Nothing
    >     Set cdb = Nothing
    > 
    >  MsgBox "Records Updated!"
    > 
    > End Sub
Springclean answered 20/7, 2015 at 17:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.