How to get a return value from store procedure, using VB6
and SQL Server
.
Stored Procedure
ALTER PROCEDURE [dbo].[DayAttn]
@Attn VARCHAR(12) OUTPUT
AS
BEGIN
SELECT @Attn = MAX(id)
FROM table1
RETURN @Attn
END
VB6
conn.Execute "exec DayAttn '" '" & Attn & "'"
The above code is showing an error.
This code should show you how to do it in VB6/ADO classic:
Set cmdTemp = New ADODB.Command
Set cmdTemp.ActiveConnection = gcnxMain
cmdTemp.Parameters.Append cmdTemp.CreateParameter("Ret", adInteger, adParamReturnValue)
cmdTemp.CommandType = adCmdStoredProc
cmdTemp.CommandText = "Procname"
cmdTemp.Execute
MsgBox "Return Value: " & cmdTemp.Parameters("Ret")
Here is how to use in/out parameters too:
Sample Stored Procedure
CREATE PROCEDURE [dbo].[TestRetVal]
@P1 int, --Parameter 1, INPUT ONLY
@P2 int OUT --Parameter 2, INPUT/OUTPUT
AS
BEGIN
DECLARE @RetVal int
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET @RetVal = @P1 + @P2 --Do whatever you need with parms
SET @P2 = 10 * @P1 --Assign value to OUTPUT parameter
RETURN @RetVal --Assign SP return value
END
VB6 Code:
Dim cnnDB As ADODB.Connection
Dim Cmd As New ADODB.Command
Dim Param As ADODB.Parameter
'Set up your cnnDB connection...
Cmd.CommandText = "TestRetVal"
Cmd.CommandType = CommandTypeEnum.adCmdStoredProc
Set Param = Cmd.CreateParameter(, adInteger, adParamReturnValue)
Cmd.Parameters.Append Param
Set Param = Cmd.CreateParameter("P1", adInteger, adParamInput, 8, 2)
Cmd.Parameters.Append Param
Set Param = Cmd.CreateParameter("P2", adInteger, adParamInputOutput, 8, 4)
Cmd.Parameters.Append Param
'Assuming a connection has been established
Set Cmd.ActiveConnection = cnnDB
Set rstTest = Cmd.Execute()
Debug.Print Cmd.Parameters(0) '--> 6 (Shows SP return value, value of the FIRST parameter added to cmd)
Debug.Print Cmd.Parameters("P2") '--> 20 (Shows current value for P2 OUT parameter)
See also how-to-get-return-value-of-a-stored-procedure (Thanks to Pecos Bill!)