C# 在C中读取SQL Server存储过程的返回值?

C# 在C中读取SQL Server存储过程的返回值?,c#,sql,sql-server,stored-procedures,C#,Sql,Sql Server,Stored Procedures,我想捕捉从C中的SQL Server存储过程返回的-1、0、1值 SQL Server: IF EXISTS(SELECT * FROM _Users WHERE UserName = @UserName AND [Password] != @Password) BEGIN RETURN -1 END IF EXISTS(SELECT * FROM _Users WHERE UserName != @UserName AND [Password] != @Password) BEGIN

我想捕捉从C中的SQL Server存储过程返回的-1、0、1值

SQL Server:

IF EXISTS(SELECT * FROM _Users WHERE UserName = @UserName AND [Password] != @Password)
BEGIN
    RETURN -1
END

IF EXISTS(SELECT * FROM _Users WHERE UserName != @UserName AND [Password] != @Password)
BEGIN
    RETURN 0
END

IF EXISTS(SELECT * FROM _Users WHERE UserName = @UserName AND [Password]= @Password)
BEGIN
    RETURN 1
END
C

我们是否能够仅仅通过按我所希望的方式更改下面代码的返回值

public User getUser(string name, string password)
{
    User user = null;

    using (var connection = Database.GetConnection())
    {
        var command = new SqlCommand("SP_GetUser @UserName, @Password", connection);
        command.Parameters.Add(new SqlParameter("UserName", name));
        command.Parameters.Add(new SqlParameter("Password", password));

        connection.Open();

        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                user = new User();
                user.UserId = Convert.ToInt32(reader["UserId"]);
                user.userName = Convert.ToString(reader["UserName"]);
                user.password = Convert.ToString(reader["Password"]);
            }
        }

        connection.Close();
    }

    return user; // I want to return -1, 0, 1
}
注:

确保设置command.CommandType=CommandType.StoredProcess;并从CommandText中删除参数,因为在使用CommandType.StoredProcess时,它只能是SP名称

创建SqlParameter时,应始终指定数据类型和比例/精度(如果相关),因为允许自动设置数据类型可能会产生意外的副作用。对参数(包括@,So)进行全名也是最佳做法

应该是

// Where the type and length match your SP
new SqlParameter("@UserName", SqlDbType.NVarChar, 128) { Value = name };
从技术上讲,存储过程的返回值表示存储过程的执行状态。您通常会使用输出参数返回用户数据。然而,在我看来,您的用例和其他用例一样好

正如@marc_s所指出的:您不应该在存储过程中使用sp_前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用sp_u,并使用其他东西作为前缀——或者根本不使用前缀


这回答了你的问题吗?旁注:存储过程不应使用sp_uu前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用sp_u,并使用其他东西作为前缀——或者根本不使用前缀!
new SqlParameter("UserName", name);
// Where the type and length match your SP
new SqlParameter("@UserName", SqlDbType.NVarChar, 128) { Value = name };