如何插入循环?

时间:2018-02-21 04:33:59

标签: sql sql-server database

我有两个问题。

1st从数据库中的不同表中获取数据

第一个查询的结果看起来像这样。 query1可以返回1行,2行或10行

acount_ID | product_ID | Color | QTY | Size | Prize | 
2         | 2          | blk   | 1   | md   | 100   |
2         | 1          | red   | 2   | md   | 50    |
2         | 9          | yllw  | 1   | sm   | 10    |
2         | 5          | wht   | 5   | lg   | 10    |


 SELECT 
    DISTINCT b.[Account_ID], bi.[Product_ID],bi.[QTY], bi.[Color],
    bi.[Size], p.[Price]  
 FROM [BAG_TB] b  
 LEFT JOIN [BAG_ITEM_TB] bi 
   on bi.[Bag_ID] = b.[Bag_ID]  
 LEFT JOIN [PRODUCT_TB] p 
   on p.[Product_ID] = bi.[Product_ID]  
 WHERE Account_ID = 2;

第二个查询是插入查询。在这个查询中,我想从query1获取所有结果并将它们插入[order_Detail_TB]。

INSERT INTO [ORDER_Detail_TB] 
(Product_ID, QTY, Color, Size, Product_Prize, Total_Prize) 
VALUES 
(@Product_ID, @QTY, @Color, @Size, @Product_Prize, @Total_Prize);

1 个答案:

答案 0 :(得分:2)

INSERT INTO [ORDER_Detail_TB] (Product_ID, QTY, Color, Size,
Product_Prize, Total_Prize)
SELECT DISTINCT  bi.[Product_ID],bi.[QTY], bi.[Color],
 bi.[Size], p.[Price]  FROM [BAG_TB] b  LEFT JOIN [BAG_ITEM_TB] bi on
 bi.[Bag_ID] = b.[Bag_ID]  LEFT JOIN [PRODUCT_TB] p on p.[Product_ID] =
 bi.[Product_ID]  WHERE Account_ID = 2;

`

更新Dublicate:https://stackoverflow.com/a/4101761/971839