-2

当我使用联合插入查询结果时,它只插入第一个查询的结果。虽然 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' 

提前致谢!

4

1 回答 1

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

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

于 2013-09-20T12:36:22.403 回答