Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting return value from stored procedure in C#

Tags:

c#

sql

sql-server

I have the following query:

set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go  ALTER PROCEDURE [dbo].[Validate] @a varchar(50), @b varchar(50) output  AS  SET @Password =  (SELECT Password FROM dbo.tblUser WHERE Login = @a)  RETURN @b GO 

This compiles perfectly fine. I want to execute this query and get the return value. My code is below:

  SqlConnection SqlConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyLocalSQLServer"].ConnectionString.ToString());         System.Data.SqlClient.SqlCommand sqlcomm = new System.Data.SqlClient.SqlCommand("Validate", SqlConn);          string returnValue = string.Empty;          try         {             SqlConn.Open();             sqlcomm.CommandType = CommandType.StoredProcedure;              SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar);             param.Direction = ParameterDirection.Input;             param.Value = Username;             sqlcomm.Parameters.Add(param);                SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);             retval.Direction = ParameterDirection.ReturnValue;               string retunvalue = (string)sqlcomm.Parameters["@b"].Value; 

Note: Exception handling cut to keep the code short. Everytime I get to the last line, null is returned. What's the logic error with this code?

like image 838
GurdeepS Avatar asked Apr 01 '09 16:04

GurdeepS


People also ask

How can we return a value in stored procedure?

Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.

Can we return from stored procedure?

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success. If no return is explicitly set, then the stored procedure returns zero. You should use the return value for status codes only.

Can procedure have return a value?

A stored procedure does not have a return value but can optionally take input, output, or input-output parameters. A stored procedure can return output through any output or input-output parameter.


1 Answers

Mehrdad makes some good points, but the main thing I noticed is that you never run the query...

SqlParameter retval = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar); retval.Direction = ParameterDirection.ReturnValue; sqlcomm.ExecuteNonQuery(); // MISSING string retunvalue = (string)sqlcomm.Parameters["@b"].Value; 
like image 191
Joel Coehoorn Avatar answered Sep 23 '22 06:09

Joel Coehoorn