Get structure of temp table (like generate sql script) and clear temp table for current instance

前端 未结 7 2160
粉色の甜心
粉色の甜心 2021-01-30 19:56

How do I get structure of temp table then delete temp table. Is there a sp_helptext for temp tables? Finally is it possible to then delete temp table in same session or query

7条回答
  •  情书的邮戳
    2021-01-30 20:14

    To Get structure of temp table

    Many of us will use common methods like Keyboard Shortcut – ‘Alt+F1‘ or will use ‘SP_HELPTEXT‘ Command (so many other methods are also there) to view the Structure of Physical Table. As we all know, Viewing the Structure of Temp Table is not as common as Viewing the Structure of Physical Table. we are going to see, how to view the Structure of Temp Table easily in SQL Server. The below mentioning methods are applicable at 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 – Using SP_HELP

    EXEC TempDB..SP_HELP #TempTable;
    

    Note-

    In the Table Structure, the Table Name shows something like ‘#TempTable__________________________________________________________________________________________________________0000000004CB’. Actually, the total length of each and every Temp Table name will be 128 . To handle the Same Temp Table name in Multiple Sessions differently, SQL Server will automatically add some underscores in between and alphanumeric’s at end.

    METHOD 2 – Using SP_COLUMNS

    EXEC TempDB..SP_COLUMNS '#TempTable';
    

    METHOD 3 – Using System Tables like INFORMATION_SCHEMA.COLUMNS, SYS.COLUMNS, SYS.TABLES

    SELECT * FROM TempDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME IN (
    SELECT NAME FROM TempDB.SYS.TABLES WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#TempTable')
    );
    GO
    
    SELECT * FROM TempDB.SYS.COLUMNS WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#TempTable');
    GO
    
    SELECT * FROM TempDB.SYS.TABLES WHERE OBJECT_ID=OBJECT_ID('TempDB.dbo.#TempTable');
    GO
    

    To Clear temp table for current instance

    IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
        DROP TABLE #TempTable;
    

提交回复
热议问题