Select into query, insert fails, but the table is created

Posted on

Question :

I am using SQL Server 2016 and I tried to the following query.

SELECT CONVERT(BIGINT, 'A') col1 INTO #tmp

This query is obviously in error. Because it does not convert. However, the temporary table (#tmp) is created even if the query fails.

Why? I think this is by design, but I want to know why.

PDW (parallel datawarehouse) does not create temporary table.

Answer :

In autocommit mode, SELECT...INTO executes 2 separate transactions. The first creates the table and the second loads the table. The table create will be committed even if the subsequent insert portion of the statement fails.

In old versions of SQL Server, both operations were done in a single atomic transaction but this was notorious for locking system tables and causing excessive blocking.

Leave a Reply

Your email address will not be published.