-2

Okay so I have this temp table. It has all the orders which a company needs to ship out. I need to somehow loop through the table and insert the information into 3+ tables.

@TempTable Table
(
    OrderID Int
)

Declare @value int = (select count(orderID) from @temptable)
Declare @i int = 1
WHILE @i < @value BEGIN
    Declare @orderid= (select first(orderid) from @temptable)
    INSERT INTO shipment (orderid, Price, Date, DateDue)
    VALUES (@orderid, @Price, @Date, @DateDue);
    Set @i += 1
    Delete top(1) from @temptable
END

Is there a better way of doing this?

Adding a little more to my issue

I'm taking in 3 values from VB.Net that as an example is @Price, @Date, and @DateDue.Because of this I wasn't able just to do a select statement cause the values are mixed with this passed values.

  • You could do that in a single query. – Juan Carlos Oropeza Sep 22 '15 at 19:08
  • 3
    possible duplicate of [SQL Insert into ... values ( SELECT ... FROM ... )](http://stackoverflow.com/questions/25969/sql-insert-into-values-select-from) – APH Sep 22 '15 at 19:09
  • Not only is it inefficient it is also potentially inaccurate. You have a delete top 1 but you don't have an order by. You also are using first but the function in sql server is first_value. – Sean Lange Sep 22 '15 at 19:13
  • @blackpluribus After your add some info this become more difficult to understand what you want. I suggest you read [**How to ask**](http://stackoverflow.com/help/how-to-ask) And [**How to create a Minimal, Complete, and Verifiable example.**](http://stackoverflow.com/help/mcve) – Juan Carlos Oropeza Sep 22 '15 at 19:43

2 Answers2

2

Do it in a single query

INSERT INTO (orderid, -some other value-)
   SELECT orderid, -some other value-
   FROM @temptable
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
0

Looping is not efficient. Always try to avoid it. You will need two queries: one for selection and inserting and one for deletion

INSERT INTO shipment (orderid, Price, Date, DateDue)
SELECT orderid, @Price, @Date, @DateDue FROM @temptable;

DELETE FROM @temptable;

Note also that the @temptable has a limited lifetime. Therefore - depending on the situation - deleting it might not be necessary at all.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188