[c#] Get Return Value from Stored procedure in asp.net

i have a stored procedure

ALTER PROC TESTLOGIN
    @UserName varchar(50),
    @password varchar(50)
As
Begin
    declare @return int;

    set @return  = (SELECT COUNT(*) 
                    FROM CPUser 
                    WHERE UserName = @UserName 
                    AND Password = @password);

    return @return;
End

and in c#

SqlConnection con = db.con;
SqlCommand cmd = new SqlCommand("TESTLOGIN", con);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter parm = new SqlParameter("@return", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;

cmd.Parameters.Add(parm);
cmd.Parameters.Add(new SqlParameter("@UserName", txtUserName.Text.ToString().Trim()));
cmd.Parameters.Add(new SqlParameter("@password", txtPassword.Text.ToString().Trim()));

cmd.ExecuteNonQuery();
con.Close();

int id = Convert.ToInt32(parm.Value);

but it always return 0. Please help me to solve this problem

This question is related to c# asp.net sql-server

The answer is


If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure

I used the following stored procedure to return the value.

CREATE PROCEDURE usp_get_count

AS
BEGIN
 DECLARE @VALUE int;

 SET @VALUE=(SELECT COUNT(*) FROM tblCar);

 RETURN @VALUE;

END
GO

Do it this way (make necessary changes in code)..

            SqlConnection con = new SqlConnection(GetConnectionString());
            con.Open();
            SqlCommand cmd = new SqlCommand("CheckUser", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter p1 = new SqlParameter("username", username.Text);
            SqlParameter p2 = new SqlParameter("password", password.Text);
            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            SqlDataReader rd = cmd.ExecuteReader();
            if(rd.HasRows)
            {
                //do the things
            }
            else
            {
                lblinfo.Text = "abc";
            }

you can try this.Add the parameter as output direction and after executing the query get the output parameter value.

  SqlParameter parmOUT = new SqlParameter("@return", SqlDbType.Int);
  parmOUT.Direction = ParameterDirection.Output;
  cmd.Parameters.Add(parmOUT);
  cmd.ExecuteNonQuery();
  int returnVALUE = (int)cmd.Parameters["@return"].Value;

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.


2 things.

  • The query has to complete on sql server before the return value is sent.

  • The results have to be captured and then finish executing before the return value gets to the object.

In English, finish the work and then retrieve the value.

this will not work:

                cmm.ExecuteReader();
                int i = (int) cmm.Parameters["@RETURN_VALUE"].Value;

This will work:

                        SqlDataReader reader = cmm.ExecuteReader();
                        reader.Close();

                        foreach (SqlParameter prm in cmd.Parameters)
                        {
                           Debug.WriteLine("");
                           Debug.WriteLine("Name " + prm.ParameterName);
                           Debug.WriteLine("Type " + prm.SqlDbType.ToString());
                           Debug.WriteLine("Size " + prm.Size.ToString());
                           Debug.WriteLine("Direction " + prm.Direction.ToString());
                           Debug.WriteLine("Value " + prm.Value);

                        }

if you are not sure check the value of the parameter before during and after the results have been processed by the reader.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd