SQL Server – Delete into New Table (Like SELECT INTO)

sql servert-sql

The select into syntax will create a new table to insert data into (I know that types may not be consistent etc. but it gives you a rough copy).

Is it possible for a delete output into statement to also create a new table in the same way, without having to define the table first?

Best Answer

Not that I know of. The OUTPUT.. INTO clause requires an existing table.

On a related note

Using SELECT.. INTO as opposed to INSERT INTO.. SELECT or OUTPUT.. INTO can have negative side-effects depending the situation. Some examples why I think you should create the table first:

  • If you're creating a table inside of a transaction, SQL Server may place a lock on (parts of) the database schema, which would prevent other users from creating, altering or dropping database objects. I'm assuming that this could even affect reading the schema, such as opening a database in Object Explorer in Management Studio. Create the table outside the transaction, then populate inside the transaction.

  • If you want to assign a clustered index to your new table, and that clustered index matches the populating query's sort order, SELECT.. INTO will create the table as a heap (unsorted), so when you apply the clustered index after, SQL Server will have to sort the contents of the table all over again.