它不会使用UNION将数据插入表中

时间:2013-09-20 10:41:42

标签: sql sql-server

当我使用union插入查询结果时,它只插入第一个查询的结果。虽然UNION之后的第二个查询未插入也未包含在内。如何使用UNION

插入两个单独查询的结果
INSERT INTO ResourceTaskFact.dbo.Region
SELECT 'Region1' AS RegionView,
       'R1'      AS RegionViewCode,
       sl.sublocationstring,
       sl.subLocationCode,
       l.locationcode,
       r.regioncode,
       rg.RegionGrpCode,
       d.DivisionCode,
       dg.DivisionGrpCode,
       --
       sl.SubLocationDescription,
       l.LocationDescription,
       r.regiondescription,
       rg.RegionGrpDescription,
       d.divisionDescription,
       dg.DivisionGrpDescription
FROM   SMECSubLocation sl,
       Location l,
       Region r,
       RegionGrp rg,
       Division d,
       DivisionGrp dg
WHERE  l.LocationCode = sl.LocationCode
       AND r.RegionCode = l.RegionCode
       AND r.RegionGrpCode = rg.RegionGrpCode
       AND d.divisioncode = rg.divisioncode
       AND d.divisiongrpcode = dg.divisiongrpcode
UNION
SELECT 'Region2',
       'R2',
       sl.sublocationstring,
       sl.subLocationCode,
       l.locationcode,
       r.regioncode,
       rg.RegionGrpCode,
       d.DivisionCode,
       dg.DivisionGrpCode,
       --
       sl.SubLocationDescription,
       l.LocationDescription,
       r.regiondescription,
       rg.RegionGrpDescription,
       d.divisionDescription,
       dg.DivisionGrpDescription
FROM   SMECVirtualSubLocation sl,
       SCVirtualLocation l,
       SCVirtualRegion r,
       SCVirtualRegionGrp rg,
       SCVirtualDivision d,
       SCVirtualDivisionGrp dg
WHERE  l.LocationCode = sl.LocationCode
       AND r.RegionCode = l.RegionCode
       AND r.RegionGrpCode = rg.RegionGrpCode
       AND d.divisioncode = rg.divisioncode
       AND d.divisiongrpcode = dg.divisiongrpcode
       AND sl.CustomOrgCode = 'DEF'
       AND l.CustomOrgCode = 'DEF'
       AND r.CustomOrgCode = 'DEF'
       AND rg.CustomOrgCode = 'DEF'
       AND d.CustomOrgCode = 'DEF'
       AND dg.CustomOrgCode = 'DEF' 

提前致谢!

1 个答案:

答案 0 :(得分:0)

  • 确保在两个SELECT中具有相同数量的列和相同类型。
  • 确保两个SELECT都返回结果。
  • 请尝试使用UNION ALL,以防两个查询返回同一行。

UNION删除重复记录(结果中的所有列都相同),UNION ALL不会。