Stored Procedures and Return Statement

In a recent interview i was been asked whether stored procedures can have “return” keyword and what type of values it can return.

I thought i will note this point here.

Stored Procedures can return value. Only a single numeric value can be returned.
Consider the following snippet.

Sql
</p>
<p>CREATE PROCEDURE dbo.GetCustomerMaxID ()<br />
AS</p>
<p>DECLARE @MAXID INT</p>
<p>SELECT MAX(ID) FROM CUSTOMER</p>
<p>Return  @MAXID</p>
<p>

and we can call the proceduce like this

Sql
</p>
<p>DECLARE @ReturnValue INT<br />
EXEC @ReturnValue = GetCustomerMaxID<br />
SELECT ReturnValue=@ReturnValue<br />

and the output looks like this:

Sql
<br />
ReturnValue<br />
-----------<br />
33343</p>
<p>(1 row(s) affected)<br />

All it does is use the RETURN statement to send back the value that was passed in.

Note The executing a RETURN statement causes a stored procedure to stop executing and return control back to the calling program.

This is often used to test for error conditions and stop processing if one is found.

and we can get the value back in to our C# – ADO.NET code like below

Sql
</p>
<p>public int GetCustomerMaxID()<br />
{</p>
<p>string connectionString =<br />
  @"Server=.SQLEXPRESS; Initial Catalog=Northwind; Integrated Security=True;";<br />
using (SqlConnection conn = new SqlConnection(connectionString))<br />
{<br />
    using (SqlCommand cmd = new SqlCommand("dbo.GetCustomerMaxID"))<br />
    {<br />
        cmd.CommandType = CommandType.StoredProcedure;</p>
<p>        SqlParameter returnValue = new SqlParameter("@Return_Value", DbType.Int32);<br />
        returnValue.Direction = ParameterDirection.ReturnValue;</p>
<p>        cmd.Parameters.Add(returnValue);</p>
<p>        conn.Open();<br />
        cmd.Connection = conn;</p>
<p>        cmd.ExecuteNonQuery();</p>
<p>        int maxID = Int32.Parse(cmd.Parameters["@Return_Value"].Value.ToString());</p>
<p>        conn.Close();</p>
<p>        return maxID;<br />
    }<br />
 }</p>
<p> return 0;<br />
}</p>
<p>

Have fun!! Happy Coding..


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

1 comment

  1. […] This post was mentioned on Twitter by Nithin Mohan T K. Nithin Mohan T K said: Stored Procedures and Return Values: In a recent interview i was been asked whether stored procedures can have “re… http://bit.ly/cYiYIO […]

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.