5

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

4

5 回答 5

6

尝试更新表格

UPDATE SALES SET totalcost=quantity*costperunit
于 2013-07-17T10:09:51.623 回答
3

You need to use update.

UPDATE SALES SET totalcost=quantity*costperunit
于 2013-07-17T10:11:36.153 回答
2

如果您不手动计算此字段,而是将其设为计算列会更好- 这样它会自动为您计算。

您可以使用以下查询更改列:

ALTER TABLE Sales
DROP COLUMN totalcost

ALTER TABLE Sales
ADD totalcost AS quantity*costperunit

演示

于 2013-07-17T10:34:20.693 回答
1

最好不要存储可计算的字段,但如果您愿意,可以使用 SQL Server 设置字段在值存在时自动计算。

于 2013-07-17T10:33:47.093 回答
1

在插入新行时试试这个

      INSERT INTO test(sno,comp_name,quantity,costperunit,totalcost)
      Values (1,@comp_name,@quantity,@costperunit,@quantity*@costperunit)
于 2013-07-17T10:20:47.877 回答