CREATE TABLE FROM CTE's

  • I have a series of complex CTE's, which I would like to use to drop the results into a table. 

    The table doesn't exist so it needs to be created, and I haven't created a new table from a CTE query before so I am a little unsure

    With CTE1 as 

    Select  Column1
              ,column2 ... 
    from table 
    )
    ,
    CTE2 as(
    Select  Column1
              ,column2 .....
    from table2
    )

    Is it as straight forward as :

    USE [database]

    Create Table NEW_TABLE
    AS( Select column1,column2,.....coulumn_N
           from CTE2) ; 

    thanks in advance

  • ExhibitA - Friday, April 21, 2017 7:40 AM

    I have a series of complex CTE's, which I would like to use to drop the results into a table. 

    The table doesn't exist so it needs to be created, and I haven't created a new table from a CTE query before so I am a little unsure

    With CTE1 as 

    Select  Column1
              ,column2 ... 
    from table 
    )
    ,
    CTE2 as(
    Select  Column1
              ,column2 .....
    from table2
    )

    Is it as straight forward as :

    USE [database]

    Create Table NEW_TABLE
    AS( Select column1,column2,.....coulumn_N
           from CTE2) ; 

    thanks in advance

    You can use SELECT X,Y,Z INTO [table_name]
    😎

  • You would need to do the inserts one at a time.
    WITH myTally(n)
    AS
    (SELECT n = ROW_NUMBER() OVER (ORDER BY (SELECT null))
    FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) a(n)
    CROSS JOIN (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) b(n)
    )
    SELECT myTally.n
    INTO tally1
    FROM myTally

  • Great stuff! 

    thanks guys

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply