SQL Server SELECT INTO and Blocking With Temp Tables

后端 未结 8 890
抹茶落季
抹茶落季 2020-12-13 19:08

So, recently a DBA is trying to tell us that we cannot use the syntax of

SELECT X, Y, Z
INTO #MyTable
FROM YourTable

To create temporary ta

8条回答
  •  猫巷女王i
    2020-12-13 20:08

    Well if that were true then mssql would have problems, since any large query can make use of tempdb to hold a copy of the rows. This can often be seen in the query plans as a table spool or can be used by the HASH JOIN operator if it runs out of memory for its buckets.

    You can look at using table variables, which mssql will try to store in memory and move to tempdb if they grow to large.

    DECLARE @foo TABLE (x int, y int, z int)
    INSERT INTO @foo(x, y, z) SELECT x, y, z FROM YourTable
    

    Of course, you should evaluate if the temporary table and copy is required first. Though if the query is complex enough that using a temp table is far more readable it might also be complex enough for a temp table to be worthwhile.

提交回复
热议问题