You are on page 1of 2

Note: Output Parameter is identified by the keyword OUTPUT.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetFruitName]
@FruitId INT,
@FruitName VARCHAR(30) OUTPUT
AS
BEGIN
SET NOCOUNT ON;

SELECT @FruitName = FruitName


FROM Fruits
WHERE FruitId = @FruitId
END

You will need to import the following namespaces.


C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

Return Output parameter from Stored Procedure in ASP.Net:

The following event handler is executed when the Button is clicked, it simply makes
a database call to the stored procedure GetFruitName (discussed earlier).
First the Input Parameter @FruitId is added along with its Value i.e. the Fruit Id
entered in the TextBox using AddWithValue method of SqlCommand Parameter class.
Next the second Parameter @FruitName is added. Since @FruitName is an Output
Parameter we cannot use AddWithValue function hence it is added using the Add
method of SqlCommand Parameter class with its Data Type and Size specified.
Once the @FruitName Parameter is added, then its Direction is set to Output since
by default the Direction of all Parameter is Input.
Once the Stored Procedure is executed, the value fetched from the Stored Procedure
is stored in the Value property of the @FruitName Output Parameter.
Finally the name of the Fruit is displayed on page using Label control.

C#

protected void Submit(object sender, EventArgs e)


{
string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetFruitName", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FruitId",
int.Parse(txtFruitId.Text.Trim()));
cmd.Parameters.Add("@FruitName", SqlDbType.VarChar, 30);
cmd.Parameters["@FruitName"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblFruitName.Text = "Fruit Name: " +
cmd.Parameters["@FruitName"].Value.ToString();
}
}
}

You might also like