将名称与ID匹配并在插入时替换

时间:2014-08-25 16:05:43

标签: sql

想象一下如下所示的插入内容:

INSERT INTO Inventory VALUES ('Product Name 1', 'Inventoried Location', Count),
('Product Name 2', 'Inventoried Location', Count),
('Product Name 3', 'Inventoried Location', Count),
...
('Product Name 1000', 'Inventoried Location', Count),
('Product Name 1001', 'Inventoried Location', Count)

有没有办法在“产品”表中将“产品名称”与其ID相匹配,并在插入时将ID替换为名称?需要在插页上为数千个条目工作。

2 个答案:

答案 0 :(得分:1)

您可以这样做:

Insert  Inventory
Select  ProductId, 'Inventoried Location', 5
From    Products 
Where   ProductName = 'Product Name'

答案 1 :(得分:1)

在这方面表现非常糟糕,但如果您仍然坚持使用该特定格式(例如,从Excel电子表格或其他内容),您可以将其写为:

INSERT INTO Inventory VALUES 
(SELECT ProductID FROM Product WHERE ProductName = 'Product Name 1', 'Inventoried Location', 5),
(SELECT ProductID FROM Product WHERE ProductName = 'Product Name 2', 'Inventoried Location', 5),
(SELECT ProductID FROM Product WHERE ProductName = 'Product Name 3', 'Inventoried Location', 5),
...
(SELECT ProductID FROM Product WHERE ProductName = 'Product Name 1000', 'Inventoried Location', 5),
(SELECT ProductID FROM Product WHERE ProductName = 'Product Name 1001', 'Inventoried Location', 5)

当然,如果您有多个具有相同ProductName的产品条目,这将会中断...

如果您想要更好的性能,可以将值插入临时表中,然后以与Siyual建议的方式类似的方式进行查找,例如,

INSERT INTO #tmpInventory (ProductName, ProductLocation, Number) VALUES 
('Product Name 1', 'Inventoried Location', 5),
('Product Name 2', 'Inventoried Location', 5),
('Product Name 3', 'Inventoried Location', 5),
.......

INSERT INTO INVENTORY (ProductID, ProductLocation, Number)
SELECT p.ProductID, t.ProductLocation, t.Number
FROM #tmpInventory t 
INNER JOIN Product p on t.ProductName = p.ProductName
相关问题