문제

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

도움이 되었습니까?

해결책

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

다른 팁

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top