SQL Server从2个不同的表中获取值,没有匹配,并插入到第3个表中

时间:2013-11-19 11:11:38

标签: sql sql-server sql-server-2008

我有两个表BusinessSector5SubCategory,我想将他们的ID插入第三个表Match_Subcategory_BusinessSector5。第3个表包含两列SubCategoryIDBusinessSector5ID

我正在使用此查询,但它无效

Insert into Match_Subcategory_BusinessSector5(SubCategoryID, BusinessSector5ID)
values(
select SubCategory.ID,[BusinessSector5].ID

from [BusinessSector5],SubCategory

where Description_DE = 'Abbrucharbeiten' and Kategorie = 'Abbruch / Entsorgung')

我收到此错误:

  

关键字选择附近的语法不正确。

2 个答案:

答案 0 :(得分:3)

使用INSERT ... SELECT:

插入时不需要使用VALUES
INSERT INTO Match_Subcategory_BusinessSector5 (SubCategoryID, BusinessSector5ID)
SELECT SubCategory.ID, [BusinessSector5].ID
FROM [BusinessSector5], SubCategory
WHERE
  Description_DE = 'Abbrucharbeiten'
  AND Kategorie = 'Abbruch / Entsorgung'

但您确定BusinessSector5SubCategory之间不需要加入吗?也许你需要这个:

INSERT INTO Match_Subcategory_BusinessSector5 (SubCategoryID, BusinessSector5ID)
VALUES
((SELECT SubCategory.ID FROM SubCategory WHERE ....),
 (SELECT [BusinessSector5].ID FROM BusinessSector5 WHERE ....));

答案 1 :(得分:1)

您不要在“选择:

”中使用“值”
Insert into Match_Subcategory_BusinessSector5 (
    SubCategoryID,
    BusinessSector5ID
)
select 
    SubCategory.ID,
    [BusinessSector5].ID
from [BusinessSector5],SubCategory
where Description_DE = 'Abbrucharbeiten' 
    and Kategorie = 'Abbruch / Entsorgung'