How to create Temp table with SELECT * INTO tempTable FROM CTE Query

前端 未结 6 1295
执笔经年
执笔经年 2020-12-04 05:39

I have a MS SQL CTE query from which I want to create a temporary table. I am not sure how to do it as it gives an Invalid Object name error.

Below is t

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 05:56

    Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.

    Select FieldA...FieldN 
    into #MyTempTable 
    from MyTable
    

    So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.

    However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.

提交回复
热议问题