Problems with passing values asp.net C #

0

I have a problem, when I assign the return from query to a variable of type object it passes as null . I have other identical methods and they work right, only the one that is not happening the right value. I was able to see that DbValue takes the right value, but at the time of assigning null pass. My code looks like this:

public string getEmailUsuario(string loginRede)
        {
            object email = "";
            string Sql;

             Sql = "SELECT EMAIL FROM VIEW_ADUSERS_LAZ_BR WHERE LOGIN_REDE = @LOGIN";

            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnIntranet"].ConnectionString;
            SqlCommand cmd = new SqlCommand(Sql, conn);

            cmd.Parameters.AddWithValue("@LOGIN", loginRede);

            try
            {
                conn.Open();

                email = cmd.ExecuteScalar(); <--- Aqui dá o erro. Passa "null"

                if (email != DBNull.Value)
                {
                    return email.ToString();
                }

                return "Sem email";

            }
            catch (Exception e)
            {
                _MSGERROR = e.Message.ToString();
                return "Sem email";
            }
            finally { conn.Close(); }
        }
    
asked by anonymous 03.06.2015 / 21:04

1 answer

2

By deducing that your LOGIN_REDE column is varchar you must include the quotation marks in @LOGIN to compare varchars.

When you move the Query to the database, it will be executed like this:

SELECT EMAIL FROM VIEW_ADUSERS_LAZ_BR WHERE LOGIN_REDE = seulogin

Instead of:

"SELECT EMAIL FROM VIEW_ADUSERS_LAZ_BR WHERE LOGIN_REDE = @LOGIN"

Use:

"SELECT EMAIL FROM VIEW_ADUSERS_LAZ_BR WHERE LOGIN_REDE = '@LOGIN'"
    
03.06.2015 / 21:15