How to update a column in all rows of a table based on values ​​in other columns (for the same row)?

I apologize in advance if SQL does not work this way, I mostly code in C ++ / C # and I don't have much experience in SQL. I basically want to iterate over each row of the table and change the column value based on the other columns. An example table might look like this:

__________________________ |first #|second #|third #| |_______|________|_______| |___1___|___1____|___0___| |___5___|___2____|___0___| |___3___|___6____|___0___| |___2___|___4____|___0___| 

Now, in pseudo code, I'm trying to get the equivalent:

 foreach row in mytable, column 3 = column 1 + column 2 

How can I get the equivalent of SQL, or it can not be done this way?

+7
source share
2 answers

It may just be like this,

 UPDATE tableName SET thirdCol = firstCol + secondCol 
+16
source

As already mentioned, a simple update can be performed using:

 UPDATE MyTable SET Column3 = Column1 + Column2; 

However, storing caclulated values, especially for simple calculations, is not good practice (there are always exceptions, and this rule is not a rule), if column3 should always be the sum of column 1 and column2, then if your DBMS allows this, you can create a calculated column .

eg. In SQL Server:

 ALTER TABLE MyTable ADD Column4 AS Column1 + Column2; 

If your DBMS does not allow calculated columns, then you can create a view, so you only save the basic data, not the calculation (again, the syntax may vary depending on the DBMS):

 CREATE VIEW myTableWithTotal AS SELECT Column1, Column2, Column1 + Column2 AS Column2 FROM MyTable 

Any of these methods ensures that the value of column3 is updated even if columns1 or columns2 are updated.

+5
source

All Articles