Quick Copy table structure with Dapper
While working through a complicated SQL series of steps I had the need to make a copy of an existing table, specifically in this case a temporary table to use for bulk loading.
The into
statement is how I would normally do this, but for an interesting variation at least in MS SQL Server I am using a SELECT TOP (0)
to only create the table structures and not fill in any of the data.
Example
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var trans = connection.BeginTransaction("MyTestTransaction");
connection.Execute(
@"SELECT TOP (0) [Id],[Name]
INTO [#TempInsert]
FROM [dbo].[MyTargetTable]", null, trans);
...
// Other statements go here to load data and do further manipulation in the
// current transaction
}
I am opening a transaction as I want my temp
table to exist for further statements and also to be rolled back and removed if failure occurs.
Other than that the code above is simply to duplicate without loading the applicable columns from the target
database table into my new temp
table.