Reputation: 1550
I have a stored procedure that will return either a 1 or 0. I cannot seem to properly wrap it in a C# function. Any help is appreciated.
Here is my stored procedure (that I've tested in SQL Server and it works):
CREATE PROCEDURE VerifyAccount
@Email VARCHAR(50),
@Pass VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Salt CHAR(25);
DECLARE @PwdWithSalt VARCHAR(125);
DECLARE @PwdHash VARBINARY(20);
SELECT @Salt = Salt, @PwdHash = Pass
FROM users
WHERE EMAIL = @Email;
SET @PwdWithSalt = @Salt + @Pass;
IF (HASHBYTES('SHA1', @PwdWithSalt) = @PwdHash)
RETURN 1;
ELSE
RETURN 0;
END;
If I open up a new SQL query and run this code, it works:
DECLARE @Result INT;
EXEC @Result = VerifyAccount
@Email = '[email protected]', @Pass = 'Str0ngP@ssw0rd!';
SELECT @Result;
When I try to wrap it in C# code, It returns a -1 value, which is not possible with this procedure. It should return a "1". What am I doing wrong?
public static int ValidateUser(User user)
{
int result = 0;
using (SqlConnection conn = new SqlConnection(SQLQuery.connDb))
{
using (var command = new SqlCommand("VerifyAccount", conn)
{
CommandType = CommandType.StoredProcedure,
Parameters =
{
new SqlParameter("@Email", user.Email),
new SqlParameter("@Pass", user.Password)
}
})
{
try
{
conn.Open();
result = command.ExecuteNonQuery();
conn.Close();
}
catch (Exception e)
{
result = -15;
Console.WriteLine(e.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
return result;
}
Upvotes: 0
Views: 584
Reputation: 657
Here is how you read the return value fro Stored Procedures.
public static int ValidateUser(User user)
{
int result = 0;
using (SqlConnection conn = new SqlConnection(SQLQuery.connDb))
{
using (var command = new SqlCommand("VerifyAccount", conn)
{
CommandType = CommandType.StoredProcedure,
Parameters =
{
new SqlParameter("@Email", user.Email),
new SqlParameter("@Pass", user.Password)
}
})
{
try
{
// STEP 01: **** SETUP UP RETURN VALUE STORED PROCEDURES *****
var returnParameter = command.Parameters.Add("@ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
conn.Open();
result = command.ExecuteNonQuery();
// STEP 02: **** READ RETURN VALUE *****
var result = returnParameter.Value;
conn.Close();
}
catch (Exception e)
{
result = -15;
Console.WriteLine(e.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
return result;
}
Upvotes: 1
Reputation: 5726
ExecuteNonQuery returns the number of rows affected
You need
result = (int)command.ExecuteScalar();
Upvotes: 4