添加额外的列和UNION

时间:2014-01-07 21:13:14

标签: sql-server-2008 union temp-tables

以下显示了尝试使用union查询以及两个额外列(fldBF和sCount)将数据插入临时表的两次尝试...

案例1:

SELECT *, 1 AS fldBF, 
          ROW_NUMBER() OVER (PARTITION BY fldPK, fldCIA ORDER BY fldPK) AS sCount 
INTO #tmpTable 
FROM V_qryCSPGA 
WHERE fldPK IN(SELECT DISTINCT thePK 
      FROM FN_qryAllDTPK()) 
UNION ALL   
SELECT * 
FROM FN_qryCSGBA() 
WHERE fldPK IN(SELECT DISTINCT thePK FROM FN_qryAllDTPK())
ORDER BY fldPK, fldCIA, fldNDat;

案例2:

SELECT * INTO #tmpTable        
FROM V_qryCSPGA 
WHERE fldPK IN(SELECT DISTINCT thePK FROM FN_qryAllDTPK()) 
UNION ALL 
SELECT *, 1 AS fldBF, 
          ROW_NUMBER() OVER (PARTITION BY fldPK, fldCIA ORDER BY fldPK) AS sCount
FROM FN_qryCSGBA() 
WHERE fldPK IN(SELECT DISTINCT thePK FROM FN_qryAllDTPK())
ORDER BY fldPK, fldCIA, fldNDat;

在任何一种情况下,我都会收到以下错误...'使用UNION,INTERSECT或EXCEPT运算符组合的所有查询必须在其目标列表中具有相同数量的表达式。反正我是否可以绕过这一点而不必进行某种其他的插入?

2 个答案:

答案 0 :(得分:1)

您需要确保两个选择查询都返回相同数量的列。根据评论,如果您需要包含额外的列,则可以将静态值添加到其他选择查询。所以,

添加(-1)作为CASE 1的静态值;

SELECT *, 1 AS fldBF, 
          ROW_NUMBER() OVER (PARTITION BY fldPK, fldCIA ORDER BY fldPK) AS sCount 
INTO #tmpTable 
FROM V_qryCSPGA 
WHERE fldPK IN(SELECT DISTINCT thePK FROM FN_qryAllDTPK()) 

UNION ALL   

SELECT *, -1 AS fldBF, -1 AS sCount --NOTE: Two static fields 
FROM FN_qryCSGBA() 
WHERE fldPK IN(SELECT DISTINCT thePK FROM FN_qryAllDTPK())
ORDER BY fldPK, fldCIA, fldNDat; 

您可以对第二个查询执行相同的操作。

答案 1 :(得分:0)

您的查询不相同。正如错误消息所示,两个 select语句必须包含相同的列。在第一个示例中,只有您的第一个选择语句包含fldBFsCount。在第二个示例中,只有第二个查询包含fldBFsCount。因为您使用的是SELECT *语法,所以如果一个表的列数多于/少于另一个表,您也会遇到此问题。

你没有发布两个输入表的外观,所以我假设它们是略有不同的表。我的建议是使用如下的查询。

您可以删除IN语句并使用联接,但我不知道您的表格是什么样的。

SELECT 
    ROW_NUMBER() OVER(ORDER BY field1) AS custField1, 
    1 AS myInt, 
    * 
INTO #tmp_tbl 
FROM (
    SELECT 
        field1, 
        field2, 
        field3, 
        'X' AS field4 
    FROM V_qryCSPGA 
    WHERE my_pk IN (SELECT DISTINCT some_pk FROM My_Fn())
    UNION ALL
    SELECT 
        'A' AS field1, 
        field5 AS field2, 
        field3, 
        field4 
    FROM FN_qryCSGBA()
) X;