使用split函数将多个值插入一个表中。可能吗?

时间:2013-03-16 05:58:15

标签: sql sql-server

我有一个列order_id来自customer_order表作为customer_order_products中的FK 3栏:

  • order_id
  • product_id
  • quantity

我想将它们同时插入到一个表中,以便它会像我这样显示:::

order_id     product_id     quantity
1              20             3
1              21             2
1              17             5

这意味着客户客户订购了3种不同的产品,其数量如上所述,生成的order_id为1。

我该如何实现呢。 需要plzzz帮助

2 个答案:

答案 0 :(得分:0)

如果我理解正确的话,普通的INSERT就足够了,你可以用一个语句插入多行

INSERT INTO customer_order_products
    ([order_id], [product_id], [quantity])
VALUES
    (1, 20, 3),
    (1, 21, 2),
    (1, 17, 5);

<强> SQLFiddle

答案 1 :(得分:0)

CREATE TABLE dbo.customer_order
 (
  order_id int
  )

CREATE TABLE dbo.customer_order_products 
 (
  product_id int,
  order_id int,
  quantity int
  )  

INSERT dbo.customer_order
VALUES(1)

INSERT dbo.customer_order_products 
VALUES(20, 1, 2),
      (20, 1, 1),
      (21, 1, 1),
      (21, 1, 1),
      (17, 1, 5)

IF OBJECT_ID('tempdb.dbo.#NewTable') IS NOT NULL DROP TABLE dbo.#NewTable
SELECT c.order_id, p.product_id, SUM(quantity) AS quantity
INTO dbo.#NewTable
FROM dbo.customer_order c JOIN dbo.customer_order_products p ON c.order_id =  p.order_id
GROUP BY c.order_id, p.product_id

SELECT *
FROM dbo.#NewTable

结果:

orde_id product_id quantity
1       17         5
1       20         3
1       21         2