Best way to add multiple items from an order into a table

When I add a request in Table TB_PEDIDOS,

TB_PEDIDOS:
ID_PEDIDO, DATA_PEDIDO, ID_CLIENTE

I also need to add the order details in 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

Do I add the details with a loop, or is there another way to do this?

The bank is SQL SERVER.

Author: Bacco, 2014-04-15

2 answers

Use Table value Constructor, for SQL-Server 2008 or higher

Http://technet.microsoft.com/en-us/library/dd776382.aspx

INSERT INTO TB_PEDIDOS (QTD, PRECO, ...)
  SELECT QTD, PRECO--, ...
    FROM ( VALUES (2, 5)
                , (1, 2)
                , (8, 3)         
         ) tPedidos (QTD, PRECO)
 1
Author: Marc.Adans, 2014-04-17 13:37:37
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(put 0 to 100 products and 0 to 1000 different prices).

 0
Author: Leonel Sanches da Silva, 2014-04-15 04:58:38