【问题标题】:Calculate the 2 columns from table and insert the result as other column in the same table计算表中的 2 列并将结果作为同一表中的其他列插入
【发布时间】:2014-09-05 17:20:52
【问题描述】:

我创建了一个表,其中包含一些列,例如 orderID、custId、unitprice、Quantity。现在我想通过乘以数量*unitprice 将另一列添加为 Totalprice。

我已通过将 totalprice 列添加到现有表中来更改表 alter table orders add totalprice int
然后我尝试使用插入查询
插入订单(总价)从订单中选择数量*单价
而且我也尝试过创建一些临时表,但临时表不会被进一步使用。

请让我知道如何输入此查询以插入列。

总价=数量*单价

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    添加列后,您不必INSERT 任何记录。你需要的是UPDATE记录。

    UPDATE Orders SET TotalPrice = Quantity * UnitPrice
    

    或者,您可以查看computed columns。这样可以省去确保Total 列与QuantityUnitPrice 列保持同步的麻烦。

    ALTER TABLE Orders ADD TotalPrice AS Quantity * UnitPrice
    

    【讨论】:

      【解决方案2】:

      您可以将此总价列设为计算列。如下....

      ALTER TABLE dbo.TableName 
      ADD  totalprice AS (quantity*unitprice)
      GO
      

      【讨论】:

      • 谢谢 M.Ali。是的,它是正确的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多