Question

I have a database with 3 tables:

Orders(OrderId, OrderDate, OrderValue)
OrderDetails(DetailsId, OrderId, ProductId, Quantity)
Products(ProductId, ProductName, Price)

I need to insert another row in Orders.

I know the OrderId, the Date but I want to calculate the OrderValue.

I don't know how to do it: the OrderValue will be something like that.

(quantity*price) where OrderDetails.ProductId=Products.ProductId for each row in OrderDetails where OrderDetails.OrderId=Orders.OrderId

Était-ce utile?

La solution

The best way is using View insted of computing OrderValue, because you should update this field every time when Quantity or Price are changed. This is not good and it contradicts 3NF also you will have a lot of other promlems. I strongly recommend to you change database structure, but if you would not change you can use following example:

insert into Orders(OrderId, OrderDate, OrderValue)
values(@SomeOrderID,getdate(), 0) 

insert into Products(ProductId, ProductName, Price)
values(/*some values*/)

insert into OrderDetails(DetailsId, OrderId, ProductId, Quantity)
values(/*some values, include @SomeOrderID*/)

update o set OrderValue = (p.Price* pd.Quantity)
from Orders o
inner join OrderDetails pd on pd.OrderId = o.OrderId
inner join Products p on p.ProductId = pd.ProductId 
where o.OrderId= @SomeOrderID

Autres conseils

If this is Oracle then you can try this

INSERT INTO orders 
            (orderid, 
             orderdate, 
             ordervalue) 
SELECT A.orderid, 
       A.orderdate, 
       A.quantity * B.price 
FROM   orderdetails A 
       inner join products B 
               ON A.productid = c.productid;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top