簡體   English   中英

循環遍歷表 SQL

[英]Looping through a table SQL

好的,我有這個臨時表。 它擁有公司需要發貨的所有訂單。 我需要以某種方式遍歷表格並將信息插入 3+ 個表格。

@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

有沒有更好的方法來做到這一點?

為我的問題添加更多內容

我從 VB.Net 中獲取 3 個值,例如@Price、@Date 和 @DateDue。因此,我無法僅執行 select 語句,因為這些值與傳遞的值混合在一起。

在單個查詢中完成

INSERT INTO (orderid, -some other value-)
   SELECT orderid, -some other value-
   FROM @temptable

循環效率不高。 總是盡量避免它。 您將需要兩個查詢:一個用於選擇和插入,一個用於刪除

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

DELETE FROM @temptable;

另請注意, @temptable的生命周期有限。 因此 - 根據情況 - 刪除它可能根本沒有必要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM