Derive parameters of a stored procedure in VBA - vba

I've tried searching a lot of places and can't quite find what I'm looking for.
I want to write a sub routine in vba that will tell me the parameters of a stored procedure stored on SQL Server.
I know how to execute a stored proc with parameters from excel vba. And I have written a stored proc that takes a stored proc name and returns the parameters. So I could use this. But I thought maybe there is a better way that I don't know about. I found a SQLCommandBuilder Class for VB that would be perfect but I need it in VBA. Is this available in VBA and I just don't know where to activate it?
Thanks
**Additional information: After the helpful comments below I am getting closer to what I am aiming to achieve.
I want to be able to pass any stored procedure into my subroutine and it will be able to figure out how many parameters it needs and what they will be
Here is my code so far
Private Sub execStoredProcedureWithParameters(strServer As String,
strDatabase As String, strSchema As String, strUSPName As String)
'Declare variables
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim intParamCount As Integer
'Open database connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=sqloledb;Data Source=" + strServer + ";Initial Catalog=" + strDatabase + ";Integrated Security=SSPI;"
conn.CommandTimeout = 0
'Here's where the connection is opened.
conn.Open
'This can be very handy to help debug!
'Debug.Print conn.ConnectionString
Set cmd = New ADODB.Command
With cmd
.CommandText = strSchema + "." + strUSPName
.CommandType = adCmdStoredProc
.ActiveConnection = conn
.Parameters.Refresh
For intParamCount = 0 To .Parameters.Count - 1
Debug.Print .Parameters(intParamCount).Name, .Parameters(intParamCount).Type, .Parameters(intParamCounti).Size, .Parameters(intParamCount).Attributes, .Parameters(intParamCount).NumericScale
' Set prm = cmd.CreateParameter(.Parameters(i).Name, adVarChar, adParamInput, 255)
' cmd.Parameters.Append prm
' cmd.Parameters(.Parameters(i).Name).Value = "DBName"
Next
End With
Set rs = New ADODB.Recordset
'Execute the Stored Procedure
Set rs = cmd.Execute
'Populate the sheet with the data from the recordset
Sheet1.Range("RecordSet").CopyFromRecordset rs
'Cleanup
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
Concerning the parameters. Is there a way to convert the DataTypeEnum from the value to the constant. So the type is currently coming through as 202 for the first parameter which I would set to adVarWChar according to this table
https://learn.microsoft.com/en-us/sql/ado/reference/ado-api/datatypeenum

You can do this with ADODB, add a reference to Microsoft ActiveX Data Objects then you can:
With New ADODB.Command
Set .ActiveConnection = myAdoDbConnection
.CommandText = "[dbo].[usp_XXX]"
.CommandType = adCmdStoredProc
.Parameters.Refresh
For i = 0 To .Parameters.Count - 1
Debug.Print .Parameters(i).Name, .Parameters(i).Type, .Parameters(i).Direction
Next
End With
There should be a necessity requiring this as it requires a round trip to the server.

Related

Is it possible to pass a parameter from MS Access to a SQL Server stored procedure and display the output in a datasheet form?

Users in MS Access enter values in a field that is passed as a parameter to a stored procedure in a SQL Server database. The stored procedure will return a result set with two columns. I would like to display that result set in a datasheet form. The code below almost does that, but will only display the final row of the result set. I confirmed that the stored procedure is being passed to the db correctly and that the test values I'm using should return 4 rows. The code in comments are a few of the many things that I have tried that didn't work.
Private Sub btnBulkLink_Click()
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
With cmd
.CommandType = adCmdStoredProc
.ActiveConnection = "Driver=SQL Server Native Client 11.0;Server=xxxxxxxxxxxxxxxxx;Database=xxxxx;Trusted_Connection=Yes"
.CommandText = "dbo.usp_FindResolutionsLinkedToServices"
.CommandTimeout = 180
.NamedParameters = True
End With
cmd.Parameters.Append cmd.CreateParameter("#PprsRefINP", adLongVarChar, adParamInput, Len(txtBulkLink.Value), txtBulkLink.Value)
Set rst = cmd.Execute
DoCmd.OpenForm FormName:="ServiceResolutionLink", View:=acFormDS, DataMode:=acFormReadOnly, WindowMode:=acHidden
' Set Forms!ServiceResolutionLink.Recordset = rst
With rst
Do While Not .EOF
Forms("ServiceResolutionLink").txtPprsRef = rst!PprsRef
Forms("ServiceResolutionLink").txtSubmissionId = rst!SubmissionId
.MoveNext
Loop
End With
' Forms("ServiceResolutionLink").txtPprsRef = rst!PprsRef
' Forms("ServiceResolutionLink").txtSubmissionId = rst!SubmissionId
' Forms("ServiceResolutionLink").Visible = True
DoCmd.OpenForm FormName:="ServiceResolutionLink", View:=acFormDS
rst.Close
End Sub
Ok, we assume you setup a pass-though query. (and it set with returns records = true).
And if your datasheet is a REAL sub form (setup as datasheet - not a table).
Then this code will work:
Private Sub Command2_Click()
With CurrentDb.QueryDefs("qryPassR")
.SQL = "exec dbo.GetHotels2 #City = '" & "Banff" & "'"
End With
Me.MyDataSheet.Form.RecordSource = "qryPassR"
End Sub
And if you are using a real datasheet (form that does not exist), then you can have the form set to
Query.PassR
The trick (or challenge) then becomes to have the form NOT load until such time you setup the query with the correct stored procedure call.
I was in the midst of testing suggestions from others when my boss figured this out. Here is our final code:
Private Sub Form_Load()
Dim rst As New ADODB.Recordset
Dim cmd As New ADODB.Command
Dim strPPRSRef As String
Dim cn As New ADODB.Connection
With cn
.Provider = "sqloledb"
cn.Properties("Data Source").Value = "[server]"
cn.Properties("Initial Catalog").Value = "[db]"
cn.CursorLocation = adUseClient
' Windows authentication.
cn.Properties("Integrated Security").Value = "SSPI"
' .CursorLocation = adUseClient
End With
cn.Open
With cmd
.CommandType = adCmdStoredProc
.ActiveConnection = cn
.CommandText = "dbo.usp_FindResolutionsLinkedToServices"
.CommandTimeout = 180
.NamedParameters = True
End With
strPPRSRef = Forms("Resolution_Tracker").txtBulkLink.Value
cmd.Parameters.Append cmd.CreateParameter("#PprsRefINP", adLongVarChar, adParamInput, Len(strPPRSRef), strPPRSRef)
With rst
.CursorType = adOpenStatic
.CursorLocation = adUseClient
End With
Set rst = cmd.Execute
Set Me.Recordset = rst
rst.Close
Set rst = Nothing
cn.Close
Set cn = Nothing
End Sub

Using Variable in SQL Query Raises ADO Error

I am trying to get a single itemcode from a SQL Server table (items) to be compared with an itemcode entered in an Excel sheet. To make this possible I have written the following VBA code in Excel 2019.
Function GetItemcodeFromSQLTable(sSQLArtikel As String) As String
Dim connection As New ADODB.connection
connection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=SQL01;Initial Catalog=110"
Dim query As String
query = "select itemcode from items where itemcode = " & sSQLArtikel
Dim rs As New ADODB.Recordset
rs.Open query, connection
connection.Close
End Function
I keep getting an error executing the line rs.open query, connection.
The purpose of this all is that I want to know if an itemcode already exists in the SQL table or not. If not, the rest of my VBA code wil create a XML file to import a new itemcode into the SQL table.
I have added a reference to "Microsoft Active X Data Objects 6.1 Library" in the VBA window.
Can anybody help me with this problem?
Many thanks.
The code I am using now is
Function CheckIfArticleCodeExistsInSQLDatabase(sSQLArtikel As String) As String
Dim query As String
Dim connection As ADODB.connection
Dim rs As ADODB.Record
Dim cmd As ADODB.Command
' PREPARED STATEMENT WITH PARAM PLACEHOLDERS
query = "select itemcode from items where itemcode = " & "'" & sSQLArtikel & "'"
' OPEN CONNECTION
Set connection = New ADODB.connection
connection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;" _
& "Data Source=SQL01;Initial Catalog=110"
' DEFINE COMMAND AND RECORDSET
Set cmd = New ADODB.Command
cmd.ActiveConnection = connection
Set rs = cmd.Execute(query, sSQLArtikel) ' BIND PARAM VALUES
' ... DO SOMETHING WITH rs
rs.Close: connection.Close
Set cmd = Nothing: Set rs = Nothing: Set connection = Nothing
End Function
When executing the command "Set rs = cmd.Execute(query, sSQLArtikel)" an errormessage is displayed "the command text is not set for the command object".
I am doing something wrong but what?
Consider the industry best practice of parameterization whenever running SQL in application layer like VBA. Doing so, you avoid the need to concatenate and punctuate variables to an SQL string.
Specifically, the missing quotes around string literals (sSQLArtikel) is your issue. With ADO Command.Execute, you can define recordsets with binded parameters.
Dim query As String
Dim connection As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
' PREPARED STATEMENT WITH PARAM PLACEHOLDERS
query = "select itemcode from items where itemcode = ?"
' OPEN CONNECTION
Set connection = New ADODB.Connection
connection.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;" _
& "Data Source=SQL01;Initial Catalog=110"
' DEFINE COMMAND AND RECORDSET
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = connection
.CommandType = adCmdText
.CommandText = query
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, _
Len(sSQLArtikel), sSQLArtikel)
Set rs = .Execute
End With
' ... DO SOMETHING WITH rs
rs.Close: connection.Close
Set cmd = Nothing: Set rs = Nothing: Set connection = Nothing

Using VBA to call a stored procedure in SQL Server, passing one parameter. I'm getting an error, multiple-step OLD DB

Going round in circles on this. I'm using VBA to call a stored procedure to pull in some data from SQL Server.
It passes one parameter which is valuation date. I have tested this SQL Server stored procedure and it works fine in sql with all dates. Now the strange thing is the query works perfectly fine from VBA and SQL for dates 10/31/2019 and previous, but for 11/30/2019 and 12/31/2019, I get an error
Run-time error '-20147217887 (8004e21)': Multiple-step OLe DB operation generated errors.
I can't figure out why it would work for the some dates but not others when it works for all date directly in SQL. Thanks in advance.
Here is the VBA code:
Sub GroupExperience()
'SQL code
Dim ValDate As Date
ValDate = Format(Range("ValDate"), "mm-dd-yyyy")
Dim rs As ADODB.Recordset
Dim cnSQL As ADODB.Connection
Dim sqlcommand As ADODB.Command, prm As Object
Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider=SQLOLEDB; Data Source=bddc1didw1;Initial Catalog=Actuarial; Trusted_connection=Yes; Integrated Security='SSPI'"
Set sqlcommand = New ADODB.Command
sqlcommand.ActiveConnection = cnSQL
'GroupExperience
sqlcommand.CommandType = adCmdStoredProc
sqlcommand.CommandText = "[HRT\akapur].[AllGroupExperience]"
Set prm = sqlcommand.CreateParameter("ValDate", adDate, adParamInput)
sqlcommand.Parameters.Append prm
sqlcommand.Parameters("ValDate").Value = ValDate
Set rs = New ADODB.Recordset
rs.CursorType = adOpenStatic
rs.LockType = adLockOptimistic
rs.Open sqlcommand
Sheets("Experience Data").Range("A2").CopyFromRecordset rs
Dim pt As PivotTable
Set pt = Sheets("Experience").PivotTables("PivotTable1")
pt.RefreshTable
End Sub

How to execute Sybase function/stored procedure from MS-Access vba?

I have a Access front end that has an ODBC connection titled fna to the Sybase back end on a server. I can easily reference the tables in the Sybase database but in the vba I need to be able to call stored procedures and functions that are in Sybase.
Function name is CalcStats.
Edit:
After reading through some of the links in the comment, I have gotten to the following code which seems to run but I can't figure out how to find the return value the function is providing.
Dim trash As String
Dim conn As ADODB.Connection
Dim cmd1 As ADODB.Command
Dim rs1 As Recordset
Set conn = New ADODB.Connection
conn.ConnectionString = "datasource=ODBC;DSN=fna"
conn.Open
Set cmd1 = New ADODB.Command
cmd1.ActiveConnection = conn
cmd1.CommandType = adCmdStoredProc
cmd1.CommandText = "CalcStats"
cmd1.Execute
Edit 2:
Finally figured out the output part. Thank you A.S.H for the links and Gord Thompson for the method for getting the connection string that for the ADODB that is needed.
So I can now create a connection, trigger the function and get the return value. However, now I'm working on the last part which is adding input parameters. I've added an input parameter to the function in sybase and saved it but I can't seem to pass an input value into the function on the Access side.
Dim trash As String
Dim conn As ADODB.Connection
Dim cmd1 As ADODB.Command
Set conn = New ADODB.Connection
conn.ConnectionString = "datasource=ODBC;DSN=fna"
conn.Open
Set cmd1 = New ADODB.Command
cmd1.ActiveConnection = conn
cmd1.CommandType = adCmdStoredProc
cmd1.CommandText = "CalcStats"
cmd1.Parameters.Append cmd1.CreateParameter("MeasurementClm", adInteger, adParamInput, , 3)
cmd1.Parameters.Append cmd1.CreateParameter("OutputValue1", adInteger, adParamReturnValue)
cmd1.Execute
trash = cmd1.Parameters.Item(0).Value
conn.Close
So the last problem I was having is that for whatever reason, I could declare an output parameter if there were no inputs but if there are inputs I had to remove the output parameter declaration. The Function output is in the parameters.item(0) position. Thanks to A.S.H and Gord Thompson for the links and suggestions. Here is the code I ended up with that is working now:
Dim trash As String
Dim conn As ADODB.Connection
Dim cmd1 As ADODB.Command
Dim rs1 As Recordset
Set conn = New ADODB.Connection
conn.ConnectionString = "datasource=ODBC;DSN=fna"
conn.Open
Set cmd1 = New ADODB.Command
cmd1.ActiveConnection = conn
cmd1.CommandType = adCmdStoredProc
cmd1.CommandText = "CalcStats"
cmd1.Parameters.Refresh
cmd1.Parameters.Append cmd1.CreateParameter("InputValue1", adInteger, adParamInput, , 3)
'cmd1.Parameters.Append cmd1.CreateParameter("OutputValue3", adInteger, adParamReturnValue)
cmd1.Execute
trash = cmd1.Parameters.Item(0).Value
conn.Close

Calling Stored Procedure while passing parameters from Access Module in VBA

I am working in Access 2010 with a Microsoft SQL Server 2008 backend. I have a stored procedure that inserts new values(supplied by the parameters) into a table. The values assigned to the parameters are obtained from files stored in a folder. The Windows File System is used to scan a particular folder to make a list of the files in it. For each scanned file the stored procedure is called and the FileName and QueueId (Filename without extension) along with other values are used as parameters for the stored procedure called. The stored procedure is used to create new records for each file for a table.
Public Function CreateInstrumentInterfaceLogRecords(BatchID As Long, InstrumentName As String) As Boolean
On Error GoTo HandleError
Dim objFSO As FileSystemObject
Dim AllFiles As Object
Dim objFolder As Object
Dim objFile As Object
Dim FileExt As String
Dim strSQL As String
CreateInstrumentInterfaceLogRecords = False
strSQL = "SELECT FileExt FROM tlkpInstrument"
FileExt = ExecuteScalar(strSQL)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(NewPath)
'NewPath is a public variable that holds the path to the folder'
Set AllFiles = objFolder.Files
For Each objFile In AllFiles
FileName = objFile.FileName
QuenueId = Replace(FileName, FileExt, "")
'call procedure to pass values'
Next objFile
ExitProc:
Exit Function
HandleError:
MsgBox Err.Number & " " & Err.Description & " in CreateInstrumentInterfaceLogRecords"
GoTo ExitProc
End Function
and the stored procedure is:
CREATE PROCEDURE upInsertToInstrumentInterfaceLog #BatchID nvarchar(60),#InstrumentName nvarchar(60) ,#FIleName nvarchar(60), #QueueId nvarchar(60)
AS
INSERT INTO tblInstrumentInterfaceLog (BatchID,InstrumentName,FileName,QueueID,DateOfBatch,Folder)
VALUES (#BatchID, #InstrumentName,#FileName, #QueueId,getdate(),'New');
GO
All the examples haven't really given me a solid idea of to create the connection and call the procedure. Some advice I have been given is to study how ExecuteNonquery works so I have been trying to find examples related to that. The following is one of the example templates I've found
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Set conn = New ADODB.Connection
conn.ConnectionString = “your connection String here”
conn.Open
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "put stored procedure name here"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
I am not really sure what I should take from this example and how to incorporate passing values. Also even though I have visited http://www.connectionstrings.com/ I am still confused on how to make them. Any help would be greatly appreciated
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Set conn = New ADODB.Connection
conn.ConnectionString = “your connection String here”
conn.Open
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "upInsertToInstrumentInterfaceLog"
cmd.parameters.Append cmd.CreateParameter("#BatchID", adVarChar, adParamInput, 60, "value for BatchID")
cmd.parameters.Append cmd.CreateParameter("#InstrumentName", adVarChar, adParamInput, 60, "value for InstrumentName")
'...
cmd.Execute
conn.Close
Use a saved pass-though query.
You code then becomes:
With currentdb.querydefs("MyPass")
.sql = "exec StoreProcName " & strBach & “,” & strInstrmentName
.execute
End With
So, you only need two lines of code here. You don't even have to declare any connection strings or even any variables if you use a saved pass-through query.