简体   繁体   中英

How to get sum value from SQL Server in C#

I try to get sum of all of my TUTAR column with SQL Server in C# but can't do it. When I try the code above it works fine.

string qry = "SELECT * FROM BENZIN WHERE DATE>='" + invoicedate + "' AND DATE<='" + invoicedate1 + "' AND PLATE= '" + plaka + "'";

conn.Open();

SqlDataReader dr = new SqlCommand(qry,conn).ExecuteReader();

while (dr.Read())
{
    var item = new ListViewItem();
    item.SubItems.Add(dr["TUTAR"].ToString());
    listView1.Items.Add(item);
}    

But when I try

string qry = "SELECT SUM(TUTAR) FROM BENZIN WHERE DATE LIKE '%" + yılcombobox.Text + "'";
MessageBox.Show(qry);

conn.Open();

SqlDataReader dr = new SqlCommand(qry, conn).ExecuteReader();

while (dr.Read())
{
    yıllıktutar = dr.GetValue(0).ToString();
}

MessageBox.Show(yıllıktutar);    

it returns nothing. yılcombobox is a textbox and it contains selected year like 2017 or 2018 or something like that

When you read a SQL result with a single value, you should call ExecuteScalar method instead of ExecuteReader() , because it lets you avoid the loop.

The most likely problem with your code is that you are performing a LIKE on a datetime column, which yields no results.

I want to get all sum(tutar) in year of 2017 or which year selected

A bigger problem is that you are not parameterizing your SQL, making it an easy target of SQL injection attacks . You should fix both problems:

conn.Open();
using (var cmd = new SqlCommand("SELECT SUM(TUTAR) FROM BENZIN WHERE YEAR(DATE)=@Year", conn)) {
    cmd.Parameters.AddWithValue("Year", int.Parse(yılcombobox.Text));
    var res = cmd.ExecuteScalar();
    if (res != DbNull.Value) {
        yıllıktutar = res.ToString();
    } else {
        yıllıktutar = "<NULL>";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM