Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Insert Sum of two columns to third column

Author  Topic 

satish.gorijala
Posting Yak Master

182 Posts

Posted - 2009-01-09 : 07:45:04
Hi i have a table with three columns

col1 col2 Result
1 4 null
2 2 null
8 3 null
6 5 null

Now i want to add col1 & col2 and insert in to column "result"

the ouput should be like this

col1 col2 Result
1 4 5
2 2 4
8 3 11
6 5 11

How to write query for this in sqlserver?


G. Satish

raky
Aged Yak Warrior

767 Posts

Posted - 2009-01-09 : 07:50:47
update yourtable
set result = isnull(col1,0)+isnull(col2,0)

select col1,col2,result from yourtable
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-01-09 : 07:51:51
Dont need a third column

select col1,col2,col1+col2 as result from your_table


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-01-09 : 07:53:02
update t
set result = s.sum
from
tab t
inner join
(select col1,col1 + col2 as sum from tab)s on s.col1 = t.col1
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-01-09 : 07:54:44
quote:
Originally posted by bklr

update t
set result = s.sum
from
tab t
inner join
(select col1,col1 + col2 as sum from tab)s on s.col1 = t.col1


Your first reply is the correct one

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Jai Krishna
Constraint Violating Yak Guru

333 Posts

Posted - 2009-01-09 : 07:55:42
U can do this by using computed columns

Jai Krishna
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-09 : 08:31:41
no need of seperate column at all as Madhi suggests. just calculate on the fly in select statement
Go to Top of Page
   

- Advertisement -