简体   繁体   中英

How do I get an SP return value?

I have done it before but just can't get it to work, I only want to do a select within my SP that returns whatever, then execute in the code-behind and then do whatever with the code returned.

The C# code

protected long getPassword(string EnteredPass) 
{
    var connectionString = ConfigurationManager.ConnectionStrings["GetConnector"].ConnectionString;
    SqlConnection dbConnection = new SqlConnection();
    dbConnection.ConnectionString = connectionString;
    SqlCommand dbCommand = new SqlCommand("PL_User_Check", dbConnection);
    dbCommand.CommandType = CommandType.StoredProcedure;

    SqlParameter abc = dbCommand.Parameters.Add("@User", SqlDbType.VarChar);
    abc.Value = EnteredPass;
    dbCommand.Parameters.Add("@ReturnValue", SqlDbType.Int, 4).Direction = ParameterDirection.ReturnValue;

    dbConnection.Open();

    dbCommand.ExecuteNonQuery();
    dbConnection.Close();
    object x = dbCommand.Parameters[""].Value;
    return Convert.ToInt64(x);
}

Stored procedure...

ALTER PROCEDURE [dbo].[PL_User_Check]
    @User VARCHAR(50),
    @ReturnValue BIGINT OUTPUT
AS

DECLARE @pass BIGINT

--Data
SET @Pass = (SELECT Pass
    FROM dbo.UserPasswords
    WHERE [User] = @User)

SET @ReturnValue = @Pass

Use:

ParameterDirection.Output

instead of:

ParameterDirection.ReturnValue

Pass the parameter in explicitly and then you can query the parameter object for its value. You are using Parameters.Add and implicitly creating the object. Method:

  1. Create parameter object for return value
  2. Add to the dbCommand explicitly

That should solve your problem.

before execute

dbCommand.AddOutParameter("@ReturnValue", DbType.Int64);

after execute

dbCommand.GetParameterValue<Int64>("@ReturnValue")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM