VBA Code to handle Output Parameter from Stored Procedure

I am using Access 2002 with an ADP project. Using VBA, I need to know how to write the code that correctly retrieves the output parameter from a SQL Server 2000 stored procedure. I have tried the following, which does not work:

Function GetSQLServerUsername() As Variant
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter

    Set cmd = New ADODB.Command
    Set prm = New ADODB.Parameter
    With cmd
        .ActiveConnection = CurrentProject.AccessConnection
        .CommandType = adCmdStoredProc
        .CommandText = "sprocGetUsername"
    End With
    With prm
        .Direction = adParamOutput
        .Name = "@Uname"
        .Type = adWChar
        .Size = 20
    End With
    cmd.Parameters.Append prm
    GetSQLServerUsername = cmd.Execute   '<<<<<<<<<<< DIES HERE

End Function

I get the following error from VBA:

Run-time error 450
Wrong number of arguments or invalid property assignment

The stored procedure I am calling is this:

CREATE PROCEDURE sprocGetUsername
     @Username nchar(20) OUTPUT
AS
     SET @Username = SUSER_SName()
GO

rgrimmAsked:
Who is Participating?
 
Alan WarrenConnect With a Mentor Commented:
Function GetSQLServerUsername() As Variant
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter

   Set cmd = New ADODB.Command
   Set prm = New ADODB.Parameter
   With cmd
       .ActiveConnection = CurrentProject.AccessConnection
       .CommandType = adCmdStoredProc
       .CommandText = "sprocGetUsername"
   End With
   With prm
       .Direction = adParamOutput
       .Name = "@Uname"
       .Type = adWChar
       .Size = 20
   End With
   cmd.Parameters.Append prm
   GetSQLServerUsername = cmd.Execute   '<<<<<<<<<<< DIES HERE

End Function


' ok
.Parameters.Append .CreateParameter("@Uname", adWChar, adParamOutput, 20)

' use this
GetSQLServerUsername = .Parameters("@Uname").Value

also tell ado not to expect a recordset

.Execute , , adExecuteNoRecords


hth
alan@cashoz.com
http://www.cashoz.com

0
 
rgrimmAuthor Commented:
Alan, excellent! Below is the Final Solution that worked. I could not find a clearly documented way of handling an output parameter from a SQL Server stored procedure in my many books and online resources. This does it about as cleanly as can be expected.

Function GetSQLServerUsername() As Variant
Dim cmd As ADODB.Command

    Set cmd = New ADODB.Command
    With cmd
        .ActiveConnection = CurrentProject.AccessConnection
        .CommandType = adCmdStoredProc
        .CommandText = "sprocGetUsername"
        .Parameters.Append .CreateParameter("@Uname", adWChar, adParamOutput, 20)
        .Execute , , adExecuteNoRecords
    End With
    GetSQLServerUsername = cmd.Parameters("@Uname").Value

End Function
0
 
Alan WarrenCommented:
Thanks rgrimm!

Regards Alan

Applications Development
Cash Australia (Int) Pty Ltd
http://www.cashoz.com
MailTo: alan@cashoz.com
 
0
All Courses

From novice to tech pro — start learning today.