简体   繁体   English

使用SQL Server Express获取存储过程的值

[英]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. 我有一个存储过程,该过程检查SQL Server数据库表中的用户名和密码。 The stored procedure returns 1 if the username and the password is correct or returns 0. Here is the code. 如果用户名和密码正确,则存储过程返回1或返回0。这是代码。 Could you please tell me how can I get the 1 or 0 pls? 您能告诉我如何获得1或0个积分吗? The rdr.toString does not work. rdr.toString不起作用。

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. 您首先必须调用一次.Read()方法来“初始化”数据读取器,然后获取第一个字段的值-假设这是您存储过程返回的所有内容,它将起作用。

You can do all of this without Reader though: 您可以在没有Reader的情况下完成所有这些操作:

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

The ExecuteScalar() exists exactly for this purpose - read one single value from database. ExecuteScalar()正是为此目的而存在的-从数据库中读取一个值。

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. 如果要使用RETURN语句从sproc返回它,则需要使用ParameterDirection = ParameterDirection.ReturnValue将另一个INTEGER参数添加到.NET代码中的SqlCommand中。

Then after executing the sproc, just retrieve the value of that param from the SqlCommand. 然后,在执行了sproc之后,只需从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". 我假设您的存储过程有一个实际的“ return”语句,该语句返回0或1。在这种情况下,将sqlparameter添加到您的命令中,并将ParameterDirection设置为“ ReturnValue”。

ExecuteNonQuery should work fine in this case. 在这种情况下,ExecuteNonQuery应该可以正常工作。

ExecuteScalar returns the value of the first column of the first row. ExecuteScalar返回第一行的第一列的值。 If you are not "returning" the 0 or 1 from the stored procedure as a query result, then that is not what you want. 如果您不是将存储过程中的0或1作为查询结果“返回”,那不是您想要的。

However, without seeing your stored procedure code I can't tell which of the two approaches is the one you need. 但是,在没有看到您的存储过程代码的情况下,我无法确定您需要哪种两种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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