简体   繁体   English

如何将计算列添加到需要连接语句的表中?

[英]How do you Add a computed column to a table that requires a join statement?

I cant figure out my syntax issue. 我无法弄清楚我的语法问题。 I am trying to ADD a computed column to an orders table. 我正在尝试将计算列添加到订单表中。 In order to do that I need to join 2 tables (Orders and Product). 为此,我需要联接2个表(“订单”和“产品”)。

ALTER TABLE tblOrder_Product
ADD [TotalCost] money 
AS (SELECT (([tbop].[Quantity])*([P].[ProductPrice]) as TotalCost)
FROM tblOrder_Product tbop INNER JOIN Product P ON tbop.ProductID = P.ProductID
GROUP BY TotalCost)

You can only add a computed column based on values in that table. 您只能基于该表中的值添加计算列。 You can create your own logical computed column if you want to create triggers to manage the value and in the trigger code you can reference the other table, but triggers are not generally recommended. 如果要创建用于管理值的触发器,则可以创建自己的逻辑计算列,并且可以在触发器代码中引用其他表,但是通常不建议使用触发器。

If you can write a scalar valued function that takes only values from your table and returns the value you're looking for, you can define the computed column with that. 如果您可以编写仅从表中获取值并返回您要查找的值的标量值函数,则可以使用该值定义计算列。 For instance, in your case: 例如,在您的情况下:

create function dbo.fn_TotalCost(@quantity int)
returns float
as
begin

    declare @r float;
    SELECT @r = @quantity*[P].[ProductPrice]
    FROM tblOrder_Product tbop INNER JOIN Product P ON tbop.ProductID = P.ProductID
    GROUP BY TotalCost;

    return @r;
end
go
alter table dbo.yourTable 
   add TotalCost as dbo.fnTotalCost(ProductID, Quantity);

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

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