Is it possible to use the SELECT INTO clause with UNION [ALL]?

Tag: ,

In SQL Server this inserts 100 records, from the Customers table into tmpFerdeen :-

SELECT top(100)*
INTO tmpFerdeen
FROM Customers

Is it possible to do a SELECT INTO across a UNION ALL SELECT :-

SELECT top(100)* 
FROM Customers
UNION All
SELECT top(100)* 
FROM CustomerEurope
UNION All
SELECT top(100)* 
FROM CustomerAsia
UNION All
SELECT top(100)* 
FROM CustomerAmericas

Not too sure where to add the INTO clause.

6 Answers

  1. scott on Mar 05, 2013

    This works in SQL Server:

    SELECT * INTO tmpFerdeen FROM (
      SELECT top 100 * 
      FROM Customers
      UNION All
      SELECT top 100 * 
      FROM CustomerEurope
      UNION All
      SELECT top 100 * 
      FROM CustomerAsia
      UNION All
      SELECT top 100 * 
      FROM CustomerAmericas
    ) as tmp
    
  2. fernando-correia on Mar 05, 2013

    SELECT * INTO tmpFerdeen FROM (your query here) data

  3. cheeseballlumpy82 on Mar 05, 2013

    SELECT * INTO tmpFerdeen FROM 
    (SELECT top(100)*  
    FROM Customers 
    UNION All 
    SELECT top(100)*  
    FROM CustomerEurope 
    UNION All 
    SELECT top(100)*  
    FROM CustomerAsia 
    UNION All 
    SELECT top(100)*  
    FROM CustomerAmericas) AS Blablabal
    

    This “Blablabal” is necessary

  4. harry on Mar 05, 2013

    You don’t need a derived table at all for this.

    Just put the INTO after the first SELECT

    SELECT top(100)* 
    INTO tmpFerdeen
    FROM Customers
    UNION All
    SELECT top(100)* 
    FROM CustomerEurope
    UNION All
    SELECT top(100)* 
    FROM CustomerAsia
    UNION All
    SELECT top(100)* 
    FROM CustomerAmericas
    
  5. rajesh on Mar 05, 2013

    Try something like this: Create the final object table, tmpFerdeen with the structure of the union.

    Then

    INSERT INTO tmpFerdeen (
    SELECT top(100)* 
    FROM Customers
    UNION All
    SELECT top(100)* 
    FROM CustomerEurope
    UNION All
    SELECT top(100)* 
    FROM CustomerAsia
    UNION All
    SELECT top(100)* 
    FROM CustomerAmericas
    )
    
  6. fernando-correia on Mar 05, 2013

    Maybe try this?

    SELECT * INTO tmpFerdeen (
    SELECT top(100)* 
    FROM Customers
    UNION All
    SELECT top(100)* 
    FROM CustomerEurope
    UNION All
    SELECT top(100)* 
    FROM CustomerAsia
    UNION All
    SELECT top(100)* 
    FROM CustomerAmericas)