计算列(Microsoft SQL Server 2014)

Computed Column (Microsoft SQL Server 2014)

图书

| B_ID |   Name  | Unit_Price|
|------+---------+-----------|
|  B01 |   Math  |     25    |
|  B02 | Science |     34    |

订单

| O_ID | B_ID |  Quantity |Total_Price|
|------+------+-----------+-----------|
|  O01 |  B01 |     2     |     ?     |
|  O02 |  B02 |     5     |     ?     |

如何通过 Order.QuantityBook.Unit_Price 相乘得到 Total_Price 其中 Order.B_IDBook.B_ID。谢谢!

听起来您需要创建一个 VIEW:

CREATE VIEW dbo.OrderPrice
AS

SELECT O.O_ID,
       O.B_ID,
       O.Quantity,
       O.Quantity * B.Unit_Price Total_Price
FROM Order O
INNER JOIN Book B
    ON O.B_ID = B.B_ID;

您可以创建一个函数,计算列将使用该函数。

CREATE FUNCTION dbo.GetTotalPrice(INT @id)
RETURNS DECIMAL(19,4)
AS 
BEGIN
   DECLARE @ret DECIMAL(19,4)
   SELECT @ret = O.Quantity * B.Unit_Price
                 FROM Order O
                   INNER JOIN Book B
                   ON O.B_ID = B.B_ID
                     WHERE B.B_ID = @id
          IF (@ret IS NULL)   
             SET @ret = 0
          RETURN @ret
END

ALTER TABLE dbo.Order
   ADD Total_Price AS dbo.GetTotalPrice(O_ID)