Nard Dog
Nard Dog

Reputation: 916

SQL Syntax help

What would be the SQL syntax to select 4 different columns in a single row in a table, add those together and then insert that value into a 5th different column in the same row? The columns are all numeric(11,2).

For example- Table name is DataCheck there is an ID that is primary key so how do I select col1, col2, col3, col4 where ID = 232...etc and add them up, and insert into col4 where id = 232...etc

Upvotes: 0

Views: 157

Answers (5)

David Chan
David Chan

Reputation: 7505

This update statement should solve your problem.

update table set col5 = col4 + col3 + col2 + col1

Upvotes: -1

Scott Bruns
Scott Bruns

Reputation: 1981

Why are you storing the calculated value in the same row?

Generally you shold not store the same data twice (in columns 1,2,3,4 and column 5). If somehow they are not equal, how will you know which column is correct?

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74197

Errr....it doesn't get much simpler than the obvious:

update myTable
set column5 = column1
            + column2
            + column3
            + column4
            + column5
where <some-where-clause>

Upvotes: 2

Justin Beckwith
Justin Beckwith

Reputation: 7866

Complete guess - but does this work?

UPDATE DataCheck SET col5=(col1+col2+col3+col4)

Upvotes: -1

Ben Hoffstein
Ben Hoffstein

Reputation: 103325

Unless I'm misunderstanding:

UPDATE MyTable SET col5 = col1 + col2 + col3 + col4 WHERE id = 232

Upvotes: 2

Related Questions