Friday, August 19, 2011

C#.NET – Get Returned Value From SQL Server Store Procedure

In this article I am going to show you, How to return value with stored procedure and how to get returned value from stored procedure with .Net

Stored procedures can return data by using RETURN keyword in SQL Server

Example:

SQL Server Script: Stored Procedure

CREATE PROCEDURE sp_return
AS
BEGIN
RETURN 1
END

C#.Net Code

try

{

SqlConnection sqlcon = new SqlConnection(“Connection String…”);

sqlcon.Open();

SqlParameter sqlParam = new SqlParameter(“@Returned”, SqlDbType.NVarChar);

sqlParam.Direction = ParameterDirection.ReturnValue;

SqlCommand cmd = new SqlCommand(“sp_return”, sqlcon);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(sqlParam);

cmd.ExecuteNonQuery();

sqlcon.Close();

string val = cmd.Parameters["@Returned"].Value.ToString();

Console.Write(val);

Console.Read();

}

catch (Exception ex)

{

Console.Write(ex.Message);

}

Output: 1

No comments: