SQL Server SELECT INTO and Blocking With Temp Tables

后端 未结 8 845
抹茶落季
抹茶落季 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条回答
  • 2020-12-13 20:04

    SELECT INTO #temp_table holds a shema lock in tempdb for the duration of the statement because part of the work it's accomplishing is creating the table. This is fundamentally different than first creating the table using CREATE TABLE #.... and then running a set based INSERT. SELECT INTO does have advantages over INSERT, in particular the operation is minimally logged if the recovery model of the database is simple or bulked log.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题