Jump to content

sum(?) return null


Go to solution Solved by M6,

Recommended Posts

Posted

boas estou a ter um problema, criei uma função para calcular a soma de alguns campos, funcionou correctamente até que apanhou campos com valor 0, ou vazio.

Agora dá erro de DBNULL ... 

Aqui está a função, alguém consegue me ajudar ?

 // Estatisticas posturas
        public int postStat(string campo, int postura)
        {
            int? total= 0;

            string s = "SELECT SUM([" + campo + "]) AS total FROM Posturas WHERE postura=@postura;";

            using (OleDbConnection con = new OleDbConnection(cfg.connectionString))
            {
                using (OleDbCommand cmd = new OleDbCommand(s, con))
                {
                    con.Open();

                    cmd.Prepare();
                    cmd.Parameters.AddWithValue("@postura", postura);

                    OleDbDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        total = Convert.ToInt32(reader["total"]);
                    }
                }
                con.Close();
            }
            return (int)total;
        }

You can't do it, kid. But don't worry, my boy. You're not the only one. No one else can do it.

Posted

Corrigido

Alterei o

total = Convert.ToInt32(reader["total"]);

por

total = reader["total"] != DBNull.Value ? Convert.ToInt32(reader["total"]) : 0;
  • Vote 1

You can't do it, kid. But don't worry, my boy. You're not the only one. No one else can do it.

  • Solution
Posted

Podes fazer isso diretamente na query, de forma a garantir que a mesma retorna sempre um valor inteiro:

string s = "SELECT ISNULL(SUM([" + campo + "]), 0) AS total FROM Posturas WHERE postura=@postura;";
  • Vote 2
10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.