Parameter does not take effect for sql command

119 Views Asked by At

I am trying to use parameters for my project but somehow it does not return an output. Please see my code below.

SqlCommand zSqlComm = new SqlCommand("SELECT * FROM tblAppUsers WHERE Username = @Username AND PasswordHash = HASHBYTES('SHA2_512', @Password)");
zSqlComm.CommandType = CommandType.Text;
zSqlComm.Parameters.AddWithValue("@Username", "admin");
zSqlComm.Parameters.AddWithValue("@Password", "admin");
return DatabaseDAL.ExecuteSelect(zSqlComm);

However if I try to use this, it returns a value from the dataset:

SqlCommand zSqlComm = new SqlCommand(
  "SELECT * FROM tblAppUsers WHERE Username = 'admin' AND PasswordHash = HASHBYTES('SHA2_512', 'admin')"
);

Please see my ExecuteSelect code:

public static DataTable ExecuteSelect (SqlCommand zSQLComm)
{
    DataTable zDataTable = new DataTable();
    SqlConnection zSQLConn = new SqlConnection(DatabaseConfiguration.ZSQLConnectionString);
    zSQLComm.Connection = zSQLConn;
    SqlDataAdapter zSQLDataAdapter = new SqlDataAdapter(zSQLComm);
    try
    {
        zSQLConn.Open();
        zSQLDataAdapter.Fill(zDataTable);    
        zSQLConn.Close();
    }
    catch
    {
        zSQLConn.Close();
    }

    return zDataTable;
}

I also tried removing the single quotes in the parameter in the CommandText but it also still did not return any output.

1

There are 1 best solutions below

1
On BEST ANSWER

As you can check by the MS SQL Server, there are different results between pass direct string and pass variable to the HASHBYTES function:

declare @Password nvarchar(50)
set @Password = 'admin'
select HASHBYTES('SHA2_512', 'admin')
select HASHBYTES('SHA2_512', @Password)

So try pass parameters with their types:

zSqlComm.Parameters.Add("@Password", SqlDbType.NVarChar, 100).Value = "admin";