Best way to create a temp table with same columns and type as a permanent table

前端 未结 6 591
长发绾君心
长发绾君心 2021-01-30 04:03

I need to create a temp table with same columns and type as a permanent table. What is the best way to do it? (The Permanent table has over 100 columns)

i.e.

Usu

相关标签:
6条回答
  • 2021-01-30 04:19

    I realize this question is extremely old, but for anyone looking for a solution specific to PostgreSQL, it's:

    CREATE TEMP TABLE tmp_table AS SELECT * FROM original_table LIMIT 0;
    

    Note, the temp table will be put into a schema like pg_temp_3.

    This will create a temporary table that will have all of the columns (without indexes) and without the data, however depending on your needs, you may want to then delete the primary key:

    ALTER TABLE pg_temp_3.tmp_table DROP COLUMN primary_key;
    

    If the original table doesn't have any data in it to begin with, you can leave off the "LIMIT 0".

    0 讨论(0)
  • 2021-01-30 04:28

    This is a MySQL-specific answer, not sure where else it works --

    You can create an empty table having the same column definitions with:

    CREATE TEMPORARY TABLE temp_foo LIKE foo;
    

    And you can create a populated copy of an existing table with:

    CREATE TEMPORARY TABLE temp_foo SELECT * FROM foo;
    

    And the following works in postgres; unfortunately the different RDBMS's don't seem very consistent here:

    CREATE TEMPORARY TABLE temp_foo AS SELECT * FROM foo;
    
    0 讨论(0)
  • 2021-01-30 04:31
    select top 0 *
    into #mytemptable
    from myrealtable
    
    0 讨论(0)
  • 2021-01-30 04:35

    Clone Temporary Table Structure to New Physical Table in SQL Server

    we will see how to Clone Temporary Table Structure to New Physical Table in SQL Server.This is applicable for both Azure SQL db and on-premises.

    Demo SQL Script

    IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
        DROP TABLE #TempTable;
    
    SELECT 1 AS ID,'Arul' AS Names
    INTO
    #TempTable;
    
    SELECT * FROM #TempTable;
    

    METHOD 1

    SELECT * INTO TempTable1 FROM #TempTable WHERE 1=0;
    
    EXEC SP_HELP TempTable1;
    

    METHOD 2

    SELECT TOP 0 * INTO TempTable1 FROM #TempTable;
    
    EXEC SP_HELP TempTable1;
    

    0 讨论(0)
  • 2021-01-30 04:38

    Sortest one...

    select top 0 * into #temptable from mytable
    

    Note : This creates an empty copy of temp, But it doesn't create a primary key

    0 讨论(0)
  • 2021-01-30 04:39
    select * into #temptable from tablename where 1<>1
    
    0 讨论(0)
提交回复
热议问题