I recently saw a comment that described getting data into a temp table using SELECT <Columns> INTO <Table>. The main reason this was done was just for convenience and to speed up getting to the answers they ultimately needed. For one off analysis or proofing this can be a very useful tool.
However, if you are going to translate that into production ready code there are relatively few places I would want to use a SELECT INTO pattern. I would much rather explicitly declare the table and insert into it. However, I do not want to spend a bunch of time tediously looking up data types and typing out column names, etc.
So what can I do?
Table Structure
You can quickly define a table structure using – you guessed it – SELECT INTO. In order to make it super quick you merely need to add a WHERE 1 = 0 clause as such.
Now to get the definition of your table:
- go to your Database
- open the Tables folder
- Right Click on the Table you selected your query into
- Select Script Table as
- Select CREATE To
- Select an Output, such as Clipboard or New Query Editor Window
This will give you an output similar to
Now all you have to do is change the table to a temporary table and make any minor modification you need such as adding primary keys.
Now you have your table.
INSERT INTO
Now you have the table, but you hate to have to type out all of those column names for the insert into. For production code I hope you list the columns in your insert statements so you do not introduce unintended errors when table structures change.
There are a couple easy ways to accomplish this.
If you are using SSDT in visual studio
- In your procedure type SELECT * FROM
- Right click on the “*”, Select “Refactor”, Select “Expand Wildcards”
- This will pop up a preview window. Press “Apply”
- You now have all the columns
- Modify the SELECT to be an INSERT INTO and paste in your original query
- Remove the INTO statement and the WHERE 1 = 0 and you are all set
If you are using SSMS (SQL Server Management Studio)
- Expand the table you created and Drag the “Columns” folder over to your query window
- Remove the INTO statement and the WHERE 1 = 0 and you are all set
Hopefully, you find these little tips and tricks can save you some time for what might otherwise be a tedious time consuming process.
Are there other tricks you use to easily turn prototype queries into production deployable code?
Let’s discuss in the comments below.