19

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

T-moty
  • 2,679
  • 1
  • 26
  • 31
Ahmad Abbasi
  • 1,776
  • 6
  • 29
  • 43
  • are you sure procedure is not returning 0 ? – adt Feb 11 '13 at 10:26
  • @adt if directly execute the procedure in SQL Server, it works correctly but in c#, it always gives 0 – Ahmad Abbasi Feb 11 '13 at 10:29
  • possible duplicate of [Getting return value from stored procedure in C#](http://stackoverflow.com/questions/706361/getting-return-value-from-stored-procedure-in-c-sharp) – Chris Diver Feb 11 '13 at 10:40

6 Answers6

41

You need a parameter with Direction set to ParameterDirection.ReturnValue in code but no need to add an extra parameter in SP. Try this

  SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
  returnParameter.Direction = ParameterDirection.ReturnValue;
  cmd.ExecuteNonQuery();

  int id = (int) returnParameter.Value;
  • thanks, running fine. (Notice than at this time `Parameters.Add` is deprecated) – dani herrera Oct 10 '13 at 13:29
  • 1
    `Parameters.Add(string parameterName, object value)` is deprecated, but `Parameters.Add(string parameterName, SqlDbType sqlDbType)` isn't. – j.i.h. Nov 25 '13 at 13:46
  • I am returning string value but its giving an exeption `Conversion failed when converting the varchar value 'my returned value' to data type int.` – SMI Mar 21 '14 at 07:39
  • 1
    please check whether you are returning the value as varchar from SP. It has to be int value. If you want to return string then it should be SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.String); – Shafeeq Koorimannil Mar 21 '14 at 13:17
  • What about one line code: `cmd.Parameters.Add("@ReturnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;` – Zeeshanef Jun 16 '14 at 15:55
2

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.

Slick
  • 21
  • 1
1

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;
Tushar Cse
  • 19
  • 5
0

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.

user1990587
  • 386
  • 4
  • 15
  • 8
    You are mistaken, a stored procedure in SQL Server *always* returns a value, which is always an `int` value too. You may have never retrieved the return value in your queries, but that doesn't mean that an SP doesn't have one. Please take a(nother) look at the [RETURN manual](http://msdn.microsoft.com/en-us/library/ms174998.aspx "RETURN (Transact-SQL)"). – Andriy M Feb 11 '13 at 14:05
  • I have retrieved the return value in my queries. But i have forget to mention this. Also i have studied at RETURN manual whose link provided by you.Thanks for link and reforming my answer. – user1990587 Feb 11 '13 at 14:29
-2

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
ase
  • 13,231
  • 4
  • 34
  • 46
  • Welcome to [so]. When answering questions, please make sure to disclose any affiliation with any references or links in the post. Thanks! – Qantas 94 Heavy Mar 16 '14 at 12:31
-3

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";
            }
Abhimanyu
  • 2,173
  • 2
  • 28
  • 44
  • This is not a nice alternative since it adds the overhead of the data reader. An output parameter is the most efficient way. – Lukos Feb 11 '13 at 13:55