I can not UPDATE my SQL Server column by SUM
and selecting the two different IDs in to tables?
Here is my code:
protected void GridView1_SelectedIndexChanged1(object sender, GridViewSelectEventArgs e)
{
txt_ID.Text = GridView1.Rows[e.NewSelectedIndex].Cells[0].Text;
}
string ObjektID = txt_ID.Text;
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlDataSource1"].ToString());
SqlCommand cmd2 = new SqlCommand();
SqlCommand cmd3 = new SqlCommand("SELECT SUM(Summe As BigInt) As SummeXY, ItemObjektID FROM [Item] GROUP BY ItemObjektID");
cmd2.CommandText = "UPDATE Objekt SET Summe = @Sum WHERE ObjektID = @ID";
try
{
conn2.Open();
cmd3.Connection = conn2;
object result = cmd3.ExecuteScalar();
cmd2.Connection = conn2;
cmd2.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(ObjektID);
cmd2.Parameters.Add("@Sum", SqlDbType.BigInt).Value = Convert.ToInt64(result);
cmd2.CommandType = CommandType.Text;
cmd2.ExecuteNonQuery();
}
2
Answers
This is, in my opinion, an XY Problem; you should not be storing aggregated data in our tables. Doing so will only cause you to endlessly chase your tail as every time the table
Item
has a DML statement run against it you need to perform one againstObjekt
too.Instead use a
VIEW
to calculate the aggregate values, and then if you need them, query that view. In it’s simplest form, theVIEW
will likely look something like this:Of course, you may well want to
JOIN
to your tableObjekt
so that you can expose other columns from that table as well.Consider performing your update as a single statement:
If we then select from the table:
We can see it has been updated with the total for the 2 ID.
As Thom explains in the other answer, this is possibly a sub-optimal strategy and it may be more effective to create a view with the totals, or perhaps a computed column, instead (depending on the source and complexity of the actual calculation).