简体   繁体   中英

Get the value of a stored procedure with SQL Server Express

I have a stored procedure which checks the username and the password from a SQL Server database table. The stored procedure returns 1 if the username and the password is correct or returns 0. Here is the code. Could you please tell me how can I get the 1 or 0 pls? The rdr.toString does not work.

SqlCommand cmd = new SqlCommand("sp_IsValidLogon", conn);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@Username", textBox1.Text));
cmd.Parameters.Add(new SqlParameter("@Password", textBox2.Text));

rdr = cmd.ExecuteReader();
label1.Text = rdr.ToString();

Try this

    label1.Text=cmd.ExecuteScalar().ToString();

instead of this:

   rdr = cmd.ExecuteReader();
    label1.Text=rdr.ToString();

This should work fine:

if (rdr.Read())
    label1.Text = rdr[0].ToString();

You first must call .Read() method once to "initialize" the data reader then take the value of the first field - assuming that's all your stored procedure returns, it will work.

You can do all of this without Reader though:

label1.Text = cmd.ExecuteScalar().ToString();

The ExecuteScalar() exists exactly for this purpose - read one single value from database.

If you are returning it from the sproc using the RETURN statement, then you need to add another INTEGER parameter to the SqlCommand in your .NET code with a ParameterDirection = ParameterDirection.ReturnValue.

Then after executing the sproc, just retrieve the value of that param from the SqlCommand.

I assume that your stored procedure has an actual "return" statement that returns 0 or 1. in that case, add a sqlparameter to your command with ParameterDirection set to "ReturnValue".

ExecuteNonQuery should work fine in this case.

ExecuteScalar returns the value of the first column of the first row. If you are not "returning" the 0 or 1 from the stored procedure as a query result, then that is not what you want.

However, without seeing your stored procedure code I can't tell which of the two approaches is the one you need.

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