-1

I have the following problem.

I have this Microsoft SQL Server query:

Select AVG(Severity) AS 'Average Severity' from VulnerabilityAlertDocument

that, executed into Microsoft SQL Server Managment Studio, return to me this float: 7,34792844929602

Now I am trying to create a C# method that simply implement this query and return the obtained value, so I have done something like this:

    public double getVulnerabilitySeverityAverage()
    {
        double vulnerabilitySeverityAverage;

        _strSQL = "Select AVG(Severity) AS 'Average Severity' from VulnerabilityAlertDocument";

        System.Data.Common.DbCommand command;
        command = _connection.CreateCommand();
        command.CommandText = _strSQL;

        vulnerabilitySeverityAverage = command.ExecuteNonQuery();

        return vulnerabilitySeverityAverage;
    }

The problem is that when the previous methos is executed the result value into vulnerabilitySeverityAverage is not the expected value (7,34792844929602) but it is the wrong value: -1.0

Why? What is it wrong? What am I missing?

Tnx

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596

2 Answers2

9

From SqlCommand.ExecuteNonQuery method

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.

Since your query is SELECT statement, so..

As a solution, you might need to use ExecuteScalar method which returns the first column of the first row in the result as an object.

vulnerabilitySeverityAverage = (double)command.ExecuteScalar();
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 6
    If only people would actually **look** at the excellent, freely available documentation! – marc_s Mar 21 '14 at 15:53
  • 1
    @marc_s Amen.. Sometimes I really hesitate should I add this information as a comment or as an answer. Because solution can be found in 30 seconds to look at their documentations. This feels bad to me. – Soner Gönül Mar 21 '14 at 15:59
1

Try to use command.ExecuteScalar() Method