Multiplying two columns of same table and storing

2020-07-13 09:11发布

I m having a table

SALES(sno,comp_name,quantity,costperunit,totalcost)

After supplying the costperunit values, totalcost need to be calculated as "totalcost=quantity*costperunit".

I want to multiply 'quantity' and 'costperunit' columns and store the result in 'totalcost' column of same table.

I have tried this:

insert into SALES(totalcost) select quantity*costperunit as res from SALES

But It failed!

Somebody please help me in achieving this.. Thanks in Advance

5条回答
孤傲高冷的网名
2楼-- · 2020-07-13 09:40

try this while inserting new row

      INSERT INTO test(sno,comp_name,quantity,costperunit,totalcost)
      Values (1,@comp_name,@quantity,@costperunit,@quantity*@costperunit)
查看更多
forever°为你锁心
3楼-- · 2020-07-13 09:41

You need to use update.

UPDATE SALES SET totalcost=quantity*costperunit
查看更多
Explosion°爆炸
4楼-- · 2020-07-13 09:50

It would be better if you do not calculate this field manually but make it a computed column instead - so it calculates automatically for you.

You can change the column with following query:

ALTER TABLE Sales
DROP COLUMN totalcost

ALTER TABLE Sales
ADD totalcost AS quantity*costperunit

DEMO

查看更多
beautiful°
5楼-- · 2020-07-13 10:05

Try updating the table

UPDATE SALES SET totalcost=quantity*costperunit
查看更多
仙女界的扛把子
6楼-- · 2020-07-13 10:05

Best not to store fields that can be calculated, but if you want to, with SQL Server you can set a field to be calculated automatically when values are there.

查看更多
登录 后发表回答