Extract OUTPUT variables from MS SQL Stored Proc





2
Date Submitted Fri. Nov. 10th, 2006 3:59 PM
Revision 1 of 1
Beginner ecliptic
Tags "VB.NET"
Comments 0 comments
For all those tirelessly searching for an efficient and effective way of pulling out stored procedure OUTPUT values using the DeriveParameters() function, here is your answer. You will want to break it up into functions and what not, but after all.. it is a snippet, not a compiled class.

Imports System.Data.SqlClient
Imports System.Data

Private m_dbconnection As New SqlConnection
Dim dbCommand As New SqlCommand

dbCommand.CommandText = sql
dbCommand.Connection = m_dbconnection
dbCommand.CommandType = Data.CommandType.StoredProcedure
dbCommand.CommandTimeout = CommandTimeout

'Derive the parameters from the stored procedure

SqlCommandBuilder.DeriveParameters(dbCommand)

Dim cmdCount As Integer
'start at 1 because @RETURN_VALUE is the first param for any stored 'procedure that has params in mssql server

For cmdCount = 1 To dbCommand.Parameters.Count - 1
                   
   If (dbCommand.Parameters(cmdCount).Direction = ParameterDirection.Input) Then
                       
 dbCommand.Parameters(cmdCount).Value = 'assign your param
                       
   ElseIf (dbCommand.Parameters(cmdCount).Direction = ParameterDirection.InputOutput) _
                    Or (dbCommand.Parameters(cmdCount).Direction = ParameterDirection.Output) Then
                        dbCommand.Parameters(cmdCount).Value = 'assign your param a default value - must do for all vars, even OUTPUT
  End If

Next

'now that the params are assigned.. let's execute and get the output 'results
'assume the sp does not return a resultset

Dim m_rows_affected as Integer
m_rows_affected = dbCommand.ExecuteNonQuery()

'use your own scheme to grab the parameter values, but here's the skeleton code for one parameter, @PARAM1 is an output param

Console.WriteLine(cmd.Parameters("@PARAM1).ToString())

'Viola.. no need to create extra objects, just execute and assign
 

Clay Zuvich

Comments

There are currently no comments for this snippet.

Voting

Votes Down


Helper jbplou