Search code examples
sql-server-2008uniontemp-tables

Adding extra columns along with a UNION


The following shows two attempts at trying to insert data into a temp table using both a union query along with two extra columns (fldBF and sCount)...

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 * 
FROM FN_qryCSGBA() 
WHERE fldPK IN(SELECT DISTINCT thePK FROM FN_qryAllDTPK())
ORDER BY fldPK, fldCIA, fldNDat;

CASE 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;

In either case I receive the following error... 'All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.' Is there anyway for me to circumvent this without having to do a whole other insert of some sort?


Solution

  • You need to make sure both select queries are returning equal number of columns. As per comments, if you need to include extra columns, you can add static values to the other select query. So,

    Adding (-1) as static values your CASE 1 would be like;

    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; 
    

    You could do the same thing to the second query.