Best way to add multiple order items to a table

Asked

Viewed 1,405 times

1

When I add a request to the table TB_PEDIDOS,

TB_PEDIDOS:
ID_PEDIDO, DATA_PEDIDO, ID_CLIENTE

I also need to add order details to another table:

TB_DETALHES_PEDIDOS:
ID_PEDIDO, ID_PRODUTO, QUANTIDADE, PRECO

Example:

Produto1 QTD:2 PRECO:5
Produto2 QTD:1 PRECO:2
Produto3 QTD:8 PRECO:3

Add the details with a loop, or is there another way to do this?

The database is SQL SERVER.

  • 1

    please improve the issue !!!

  • see if you can understand now..

  • 1

    @Gerson, your question is a little confusing, but from what I understand you want to know if there is any way to insert data into 2 tables in the same insert, to add the order and items into a single insert? Is that it? Something like a insert in cascade?

  • you are using some Framework ?

2 answers

1

0

INSERT TB_DETALHES_PEDIDOS (ID_PEDIDO, ID_PRODUTO, QUANTIDADE, PRECO)
SELECT pe.ID_PEDIDO, pd.ID_PRODUTO, RAND() * 100, RAND() * 1000
FROM TB_PEDIDO pe
CROSS JOIN TB_PRODUTO pd

RAND() generates a number between 0 and 1. I put 100 for product and 1000 for price just as examples (puts from 0 to 100 products and from 0 to 1000 different prices).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.