简体   繁体   中英

SQL Field as a query result

i have a database for a restaurant. a table for the item (itemid,itemname,price) and a table for orders (orderid,itemid,quantity,price). i have the price field in the orders table just because if the price in the item table was changed the order value of course shouldn't be changed. Is there anyway to automate the price to be set? i cant seem to do this:

    CREATE TABLE ORDER(
    OrderID INT IDENTITY(1,1) PRIMARY KEY,
    ItemID INT NOT NULL,
    Quantity INT NOT NULL,
    Price MONEY AS (SELECT Price FROM ITEM)
    );

If you have are writing the only application(s) which will INSERT new rows, then set the price on an order row when you INSERT it.

Otherwise, consider a trigger which will execute whenever a row is inserted into that table by anybody anywhere. It can look up the item price and set the value on the order before the record is written to the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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