我正在尝试将产品批量映射到catergoryID表。每个产品都有一个SKU代码,然后映射到CategoryID表。该脚本执行正常,但当我看到产品没有映射。知道我哪里错了吗?是因为prodcutID已经存在了吗?
create table tmp_products (ProductID int, SKU nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS, CategoryID int)
insert into tmp_products (SKU, CategoryID) values ('CLFLNW1',1252)
insert into tmp_products (SKU, CategoryID) values ('CLFROCR013',1252)
insert into tmp_products (SKU, CategoryID) values ('GBLGOKOM',1252)
insert into tmp_products (SKU, CategoryID) values ('HS008714',1252)
insert into tmp_products (SKU, CategoryID) values ('HS014928',1252)
insert into tmp_products (SKU, CategoryID) values ('HS400085',1252)
insert into tmp_products (SKU, CategoryID) values ('HS400093',1252)
insert into tmp_products (SKU, CategoryID) values ('HS400101',1252)
insert into tmp_products (SKU, CategoryID) values ('HS400135',1252)
update tmp_products
set ProductID = p.ProductID
from product p
join tmp_products t on t.SKU = p.SKU
insert into ProductCategory (ProductID, CategoryID, DisplayOrder)
select ProductID, CategoryID, 1
from tmp_products
where ProductID not in
(select pc.ProductID
from ProductCategory pc
join tmp_products tp on tp.ProductID = pc.ProductID)
and ProductID is not null
drop table tmp_products
答案 0 :(得分:1)
您的INSERT
无法添加其他类别;一旦产品在表ProductCategory
中有一个类别,就不会再添加。
您可以在子查询中添加WHERE
条件:
WHERE pc.CategoryID = tmp_products.CategoryID
完整的INSERT
语句现在变为:
INSERT INTO ProductCategory (ProductID, CategoryID, DisplayOrder)
SELECT ProductID, CategoryID, 1
FROM tmp_products
WHERE ProductID NOT IN (
SELECT pc.ProductID
FROM ProductCategory pc
JOIN tmp_products tp ON tp.ProductID = pc.ProductID
WHERE pc.CategoryID = tmp_products.CategoryID
)
AND ProductID IS NOT NULL