Search code examples
sqlsql-serversql-server-2014calculated-columnscomputed-field

Computed Column (Microsoft SQL Server 2014)


Book

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

Order

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

How can I get the Total_Price by multiplying Order.Quantity and Book.Unit_Price where Order.B_ID is a FK to Book.B_ID. Thank you!


Solution

  • You can create a function where the computed column would use the function.

    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)