【问题标题】:How to create a computed column that references another column from another table?如何创建一个引用另一个表中的另一列的计算列?
【发布时间】:2016-01-09 17:10:44
【问题描述】:

我正在使用 Microsoft SQL Server,并且仍在学习。我有两个表,一个产品表和一个订单详细信息表。产品表包含价格,然后订单明细表包含对产品、产品数量和总价的参考。这是两张表:

--Create Product Table
CREATE TABLE Products.Product  
(
    product_id          INT             NOT NULL    PRIMARY KEY IDENTITY,
    product_name        VARCHAR(40)     NOT NULL,
    product_desc        VARCHAR(5000),
    product_price       SMALLMONEY      NOT NULL    CHECK (product_price >= 0)
);

--Create Order Details Table
CREATE TABLE Orders.Order_detail 
(
    order_detail_id     INT             NOT NULL    PRIMARY KEY IDENTITY,
    product_id          INT             NOT NULL,
    product_quantity    INT             NOT NULL    CHECK (product_quantity >= 0),
    order_detail_total  MONEY           NOT NULL,

    FOREIGN KEY (product_id)        REFERENCES Products.Product
);

我怎样才能使 order_detail_total 成为 product_price * product_quantity 的计算列?

【问题讨论】:

  • 嗨@kingcobra1986,我这里没有sqlserver,但根据msoft 的说法,似乎无法从另一个表创建计算列。但是,您可以创建一个函数来帮助您这样做...stackoverflow.com/questions/6867047/…
  • 计算列不能引用其他表。
  • 我想您可以为此使用触发器。不过,我个人会在数据库层之上的一层处理这个问题。
  • 我支持@TT,您正在尝试的是业务逻辑层问题,而不是数据层问题
  • 我这样做有两个原因,我在一个数据库类中,我们只是专注于数据库而不使用任何其他语言或任何东西来计算它,我希望列变得充实。另一个原因只是为了学习。这不适用于任何实际项目。

标签: sql-server tsql


【解决方案1】:

感谢@Andy K,我想出了这个解决方案:

--Create Product Table
CREATE TABLE Products.Product  
(
    product_id          INT             NOT NULL    PRIMARY KEY IDENTITY,
    product_name        VARCHAR(40)     NOT NULL,
    product_desc        VARCHAR(5000),
    product_price       SMALLMONEY      NOT NULL    CHECK (product_price >= 0)
);
GO

--Create a function to calculate the order details total
CREATE FUNCTION Orders.calcOrderDetailTotal(@quantity INT, @productId INT)
RETURNS MONEY
AS
BEGIN
    DECLARE @price SMALLMONEY
    SELECT @price = product_price FROM Products.Product AS TP 
           WHERE TP.product_id = @productId
    RETURN @quantity * @price
END
GO

--Create Order Details Table
CREATE TABLE Orders.Order_detail 
(
    order_detail_id     INT             NOT NULL    PRIMARY KEY IDENTITY,
    product_id          INT             NOT NULL,
    product_quantity    INT             NOT NULL    CHECK (product_quantity >= 0),
    order_detail_total  MONEY           NOT NULL,

    FOREIGN KEY (product_id)        REFERENCES Products.Product
);

这对我创建的测试数据库很有用。

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 2013-12-08
    • 2018-08-13
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多