UNION,INTERSECT或EXCEPT SQL服务器中的组合查询给出错误

时间:2015-08-05 07:00:27

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

我有以下查询。我在SQL server 2008 r2中运行它。

DECLARE @PartNo Char(22)
DECLARE @PartIssue AS CHAR(4)
DECLARE @Level AS INT
SELECT @PartIssue = drawissno, @PartNo = partnum, @Level=1 FROM partmaster  where partnum = 'AE40-0287810'

WITH Hierarchyct(BOMLevel,bmchild, bmparent, bmqty, leadtime, childissue,bmethod,rmethod, requiredqty) AS

      (SELECT     @Level AS BOMLevel,
                        @PartNo AS bomchild, 
                        cast('' AS CHAR(22)) AS bomparent,  
                        cast(1.0 AS FLOAT) AS bomqty, 
                        (SELECT stleadtim FROM stock WHERE stocknum = @PartNo) AS leadt,
                        @PartIssue as childissue, 
                        eccbom AS bmethod, 
                        eccroute as rmethod,
                        cast(1.0 AS FLOAT) AS requiredqty 
      FROM eccissue 
      WHERE eccpart = @PartNo AND eccissueno = @PartIssue 

      UNION ALL

      SELECT            (hierarchyct.BOMLevel + 1) AS BOMLevel,
                        bom.bomchild, 
                        bom.bomparent, 
                        bom.bomqty, 
                         (CASE WHEN LTRIM(RTRIM(bom.bomissue)) = 'CURR' THEN (SELECT drawissno FROM PartMaster WHERE PartNum = bom.bomchild) ELSE bom.bomissue END) AS childissue,
                        bom.baltmethod AS bmethod,    
                        (SELECT eccroute FROM eccissue WHERE eccissue.eccissueno = (CASE WHEN LTRIM(RTRIM(bom.bomissue)) = 'CURR' THEN (SELECT drawissno FROM PartMaster WHERE PartNum = bom.bomchild) ELSE bom.bomissue END) AND eccissue.eccpart = bom.bomchild ) as rmethod,
                        (bom.bomqty * hierarchyct.requiredqty) AS requiredqty
      FROM         bom  INNER JOIN hierarchyct ON bom.bomparent = hierarchyct.bmchild  
      WHERE bom.baltmethod =(SELECT eccbom FROM eccissue WHERE eccissue.eccpart = hierarchyct.bmchild AND eccissue.eccissueno = hierarchyct.childissue )
      )
SELECT      hierarchyct.*
      FROM  hierarchyct

当我运行它时,我收到一条消息说:

  

Msg 205,Level 16,State 1,Line 6
  使用UNION,INTERSECT或EXCEPT运算符组合的所有查询在目标列表中必须具有相同数量的表达式。

我检查了语法,看起来很好,但这个问题并没有得到解决。关于这个问题的任何想法?

提前致谢。

2 个答案:

答案 0 :(得分:1)

你错过了

的等价物
(SELECT stleadtim FROM stock WHERE stocknum = @PartNo) AS leadt,

在你的第二个工会会员

答案 1 :(得分:1)

您的查询的第二部分缺少[leadt]列。