MS Access to Execute Proc in SQL Server - sql-server

I have a Proc for creating and updating a table in SQL Sever. The result table is linked to the MS ACCESS FE. It was before created by Macro involving queries in MS Access. How could I call or execute the Proc from MS Access FE.
I tried this code but it doesn't result in anything.
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = "Provider=SQLNCLI11.1;Security=SSPI;Initial Catalog=MYDB;Server=MyServer;Integrated Security=SSPI;"
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "UPDATE_DATA"
cmd.Execute
I'm new to VBA Coding. Any help or leads will be greatly appreciated.

In your code, you haven't opened a connection to the database. Open a connection first like in the below code:
Private Const gcConn As String = "Provider=SQLNCLI11.1;Security=SSPI;Initial Catalog=MYDB;Server=MyServer;Integrated Security=SSPI;"
Sub UpdateProc()
Dim oDB As ADODB.Connection
Dim oCM As ADODB.Command
Set oDB = New ADODB.Connection
oDB.Open gcConn
Set oCM = New ADODB.Command
With oCM
.ActiveConnection = oDB
.CommandType = adCmdStoredProc
.CommandText = "UPDATE_DATA"
.Execute
End With
oDB.Close
Set oDB = Nothing
End Sub

Simply save your command as a pass-though query. Thus your query is:
UPDATE_DATA
Then this one line of code will run that query
CurrentDb.QueryDefs("MyPass").Execute

Related

Import data from Excel into SQL Server using queries

If I am not allowed to use the import function of SQL Server to bring data from Excel into SQL Server, would you be able to use queries to import the data?
There are several ways to export data from Excel to SQL Server. Here is one concept.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=server_name"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=server_name;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub

VBA to open and run .sql file and copy the result in excel

I am a bit new to this so my apologies in advance for any mistakes. I am trying to open and execute a sql query which is saved in C drive. The sql works fine. I did not write that sql and it is a very big file so would not like to add the code in VBA. I have been searching on this site and other places but struggling to make this work. I have had some or the other problem each time. I am pasting the code below for you to have a look and help me please. I have created this function which I am using in my VBA code.
Public Function ss()
'Open Connection
Dim oCon As ADODB.Connection
Set oCon = New ADODB.Connection
'Set Connection String
Dim sCon As String
sCon = "Provider=SQLOLEDB;Persist Security Info=True;User
ID='*****';Password='*****';Initial Catalog=****;Data Source=*******;Use
Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption
for Data=False;Tag with column collation when possible=False"
oCon.Open sCon 'Connect established
'Create recordset
Dim ps As ADODB.Recordset
Set ps = New ADODB.Recordset
'Set & execute SQL Command
Dim pCMD As ADODB.Command
Set pCMD = New ADODB.Command
Set pCMD.ActiveConnection = oCon
Dim filename As String
filename = "C:\Users\???????????\******.sql"
'select data
pCMD.CommandText =
CreateObject("scripting.filesystemobject").opentextfile(filename).ReadAll()
Set ps = pCMD.Execute(, , adCmdText)
Debug.Print ps.GetRows
If ps.EOF = False Then Sheets("Sheet2").Range("A1").CopyFromRecordset ps
'Close connection
Set ps = Nothing
Set pCMD = Nothing
oCon.Close
Set oCon = Nothing
End Function
Debug.Print has only been used to see the result but it is showing the same error "Run-time error '3704' Operations is not allowed when the object is closed. After trying so many different things I am not sure what is it that I am doing wrong.
Can someone please help?
Any help will be really appreciated.
For me the easiest solution for you is to modify the end of the stored procedure so when executed, it insert all the results in a table. The next time you execute the SP you just have to TRUCATE the table and INSERT new results.
Execute the SP
You can call the SP from Excel with VBA using some code you can find here on StackOverflow, for example the following (which I've taken from this answer):
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = 1 ' adCmdText
cmd.CommandTimeout = 120 ' number of seconds to time out
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Dim SQL As String
SQL = "EXEC [dbo].[Procedure_make_report] 'param1'"
cnn.Open
cmd.CommandText = SQL
cmd.ActiveConnection = cnn
cmd.Execute
If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If
Retrive results into Excel
Now that the results of the SP are stored into a table of you DB you can import them into Excel with ODBC connection as shown here or with this procedure.

vba mssql connection error

I am trying to connect sql with Access.
What I want to do is simply get data from mssql using select statement.
Here is the code.
Sub ConnectSQLServer()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Dim par As ADODB.Parameter
Dim strSQL As String
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
strSQL = "SELECT * FROM dbo.Version"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
End Sub
When I execute this code, I get error like "[Microsoft][ODBC SQL Server Driver][SQL Server] The request for procedure 'Version' failed because 'Version' is a table object.'
I know that I need to add something after "strSQL = SELECT * FROM dbo.Version" but I do not know exactly how to fill in.
Could you please help me with this?
It looks like you are executing dbo.Version as a SP or a SQL Command which is wrong.
You should execute the command in strSQL object instead. So after the modifications your code will look something like this:
strSQL = "SELECT * FROM dbo.Version"
Set cmd = New ADODB.Command
cmd.CommandText = strSQL
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
EDIT 1
I replicated the same issue in MS Excel to read data from MS SQl Server by using the following code and it worked for me:
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=HARSH-SHARMA\SQLEXPRESS;Initial Catalog=db1;User ID=sa;Password=pass001;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from Subject"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
Please try this.

How to supply parameters to sql server procedure

I'm currently executing this code from ms access which calls a stored procedure from SQL server to create a temporary table and export the data in that table directly to excel workbook. I'm now looking to have two date fields from my form to be parameters (dateOpen, dateClose) for this procedure. How would I do this?
Dim rst As New ADODB.Recordset
Dim cmd1 As New ADODB.Command
Dim cmd2 As New ADODB.Command
Dim cmd3 As New ADODB.Command
With cmd1
.ActiveConnection = CurrentProject.connection
.CommandText = "usp_tbl_close"
End With
Set rst = cmd1.Execute
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "dbo.close", "C:\Documents\testio3.xls", True, "close"
Use the create and append parameter methods in ADO DB.
Here is a link to a MSDN article that should help.
try this
With cmd1
.ActiveConnection = CurrentProject.connection
.CommandText = "usp_tbl_close"
.CommandType = 4
.Parameters("#paramname1") = paramvalue1
.Parameters("#paramname2") = paramvalue2
.execute
End With

Run stored procedure: user type not defined error

I am trying to run the following Stored Procedure on the click of the OK Button:
Private Sub ok_Click()
Dim objConnection As New ADODB.Connection
Dim objCom As ADODB.Command
Dim provStr As String
Set objCom = New ADODB.Command
objConnection.Provider = "sqloledb"
provStr = "Data Source=Server Name;" & "Initial Catalog=DB NAME;User Id=USERNAME;Password=Password;"
objConnection.Open provStr
With objCom
.ActiveConnection = objConnection
.CommandText = "dbo.ix_spc_planogram_match 74"
.CommandType = adCmdStoredProc
.Execute
End With
End Sub
The error is:User type not defined. The stored procedure runs correctly in SQL Server Management Studio.
Check your references, in particular ensure you are referencing the Microsoft ActiveX Data Objects x.x Library.

Resources