While working on reports my wife ask me "Is there a way I can do bulk insert into a temporary table without enumerating the columns needed?". The next day the same question was ask by my coleague in our office. Looks like a FAQ to me so I decided to add this in my blog. If I was ask a couple of times in a week there might be thousands asking the same question in the world. Now here it is.
The SELECT INTO will do the trick for you. SELECT INTO is a SQL command that do bulk insert into a table and automatically creates the the destination table for you if it does not exist. Unlike INSERT INTO, it requires you to expicitly define the columns of the destination table. Be sure to explicitly drop the table after using.
Sample 1. Normal Usage.
This will insert all the records and columns into the temporary table #testtable
SELECT *
INTO #testtable
FROM Employees
DROP TABLE #testtable
Sample 2. Adding unique column to the record.
This will insert all the records including a unique column ColID to uniquely identify the record.
SELECT NEWID() as ColID, *
INTO #testtable
FROM Employees
DROP TABLE #testtable
You can use this tirck for temporary storage and data caching for your complex queries. Hope this helps.