简体   繁体   English

如何使用存储过程从 t-sql 表中现有的两列计算一列的值?

[英]How to compute value for one column from existing two columns in a table in t-sql using stored procedure?

In the below mentioned table I want to compute TotalCost as在下面提到的表中,我想将TotalCost计算为

TotalCost = Quantity * UnitPrice

How can I create a stored procedure to do so?我怎样才能创建一个存储过程来做到这一点? Is it possible or not?有没有可能?

CREATE Table SalesTransaction
(
    SalesOrderNO int PRIMARY KEY NOT NULL,
    ProductId int FOREIGN KEY REFERENCES Product(ProductId),
    Quantity int,
    UnitPrice decimal,
    TotalCost decimal,
    DateOfSale date,
)

You wouldn't.你不会的。 Your syntax looks like SQL Server.您的语法看起来像 SQL 服务器。 You can just use a computed column:您可以只使用计算列:

alter table SalesTransaction add TotalCost as (Quantity * UnitPrice);

Voila.瞧。 The column is now part of the table definition.该列现在是表定义的一部分。 And it is always up-to-date.而且它始终是最新的。

This assumes that quantity is some sort of number.这假设quantity是某种数字。 But then again, your formula already assumes that, so you should fix the data model.但是话又说回来,你的公式已经假设了,所以你应该修复数据 model。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM