如何从 Windows 形式的存储过程中获取 return 值 C#

How to get return value from stored procedure in Windows form C#

这是我的程序:

DECLARE @ReturnValue int

SELECT @ReturnValue = idUser
FROM Users
WHERE Alias = @UserAlias AND Password = @UserPassword 

RETURN @ReturnValue

这是我的 C# 代码,我希望我可以从该过程中检索值:

TeamPWSecureBD.Open(); //Open SQL Connection

string alias = textBoxUsernameLogin.Text.Trim();
string pass = textBoxPasswordLogin.Text;

SqlCommand LoginVerify = new SqlCommand("_spUserVerify", TeamPWSecureBD);
LoginVerify.CommandType = CommandType.StoredProcedure;

LoginVerify.Parameters.AddWithValue("@UserAlias", alias);
LoginVerify.Parameters.AddWithValue("@UserPassword", pass);

SqlDataReader UserVerify = LoginVerify.ExecuteReader();

//Se o valor retornado pelo sp for 0 significa que o user não existe.
//O sp retorna o id do utilizador se o username e a password estiverem corretas.
//O id de utilizador menor é o 7.
if (Convert.ToInt32(UserVerify.GetSqlValue(0)) == 0)
    MessageBox.Show("Invalid username/password.", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
    GlobalVariables.UserLoggedIn = Convert.ToInt32(UserVerify.GetSqlValue(0));
    PWLists MainForm = new PWLists();
    MainForm.ShowDialog();
    this.Close();
}

我在SQL服务器执行程序时,返回值是正确的。

但是一旦我尝试以这种形式阅读它,它就会因错误而崩溃:

invalid attempt to read when no data is present

尝试:

SELECT @ReturnValue

而不是:

RETURN @ReturnValue

如果您想捕获存储过程执行的 RETURN 语句的值,您需要向 SqlCommand

添加另一个参数
 SqlParameter r = LoginVerify.Parameters.Add("@return", SqlDbType.Int);
 r.Direction = ParameterDirection.ReturnValue;
 r.Value = 0;
 SqlDataReader UserVerify = LoginVerify.ExecuteReader();

 // Now you need to complete the reading from the UserVerify reader and 
 // finally you can catch the return value 
 .....

 UserVerify.Close();
 int result = (int)r.Value;

但是,考虑到您的 StoredProcedure 代码,我认为您可以简单地避免声明另一个参数以及 SqlDataReader,因为您似乎 return 只有一行和一个字段。 ExecuteScalar 的确切范围...

SP 现在只是 select

SELECT idUser FROM Users 
WHERE Alias = @UserAlias AND Password = @UserPassword 

检索 idUser 的代码是

object result = LoginVerify.ExecuteScalar();

if (result == null)
    MessageBox.Show("Invalid username/password.", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
    GlobalVariables.UserLoggedIn = Convert.ToInt32(result);
    PWLists MainForm = new PWLists();
    MainForm.ShowDialog();
    this.Close();
}