Introduction
When using the Microsoft Data Access in your Application and accessing your Microsoft SQL Server 2008 database and the CommandType is a stored procedure, there may be a need to pass input parameters to the stored procedure and get an output or a return value coming from the stored procedure. This article will show you the basic way on how to use the SqlParameter Direction (Input, InputOutput, Output and RetrunValue)
Direction
|
Description
|
Input (Default)
|
The parameter is an input parameter.
|
Output
|
The parameter is an output parameter.
|
InputOutput
|
The parameter is capable of both input and output.
|
ReturnValue
|
The parameter represents a return value from an operation such as a stored
procedure
|
Code
C#
private int Execute(ref object outputParam,ref object inoutParam)
{
string oUsername = "Jelo";
int InOutParamValue = 3;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "MyStoredProcedure";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter oParam = new SqlParameter("@Username", oUsername);
oParam.SqlDbType = SqlDbType.VarChar;
cmd.Parameters.Add(oParam);
SqlParameter OutputParam = new SqlParameter("@OutputParam", SqlDbType.VarChar);
OutputParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(OutputParam);
SqlParameter InOutParam = new SqlParameter("@InputOutputParam", InOutParamValue);
InOutParam.SqlDbType = SqlDbType.Int;
InOutParam.Direction = ParameterDirection.InputOutput;
cmd.Parameters.Add(InOutParam);
SqlParameter RetParam = new SqlParameter("ReturnValue", DBNull.Value);
RetParam.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(RetParam);
cmd.ExecuteNonQuery();
int IntReturn = Convert.ToInt32(cmd.Parameters["ReturnValue"].Value);
if (IntReturn == 1)
{
outputParam = cmd.Parameters["@OutputParam"].Value;
inoutParam = cmd.Parameters["@InputOutputParam"].Value;
}
return IntReturn;
}
conn.Close();
}
Stored Procedure
ALTER PROCEDURE MyStoredProcedure
@Username VARCHAR(100),
@OutputParam VARCHAR(100) OUTPUT,
@InputOutputParam INT OUTPUT
AS
BEGIN
IF EXISTS(SELECT * FROM dbo.Table1 WHERE MemberCode = @Username AND id < @InputOutputParam)
BEGIN
SELECT @OutputParam = MAX(ReferenceNo),@InputOutputParam = MAX(id) FROM dbo.Table1
WHERE MemberCode = @Username
RETURN 1
END
ELSE
BEGIN
RETURN -1
END
END
Hope it helps someone!