I have a SQL query (SQL Server) and it generate reports, I want to store that exact report in temp table so I can play with it later. Now question is do I need to create temp table first and then store SQL query result into it, or is there any way to dynamically create table and store query result?
You can use select ... into ... to create and populate a temp table and then query the temp table to return the result. No you don't. If you want to fill a table that already exist with rows you need to use a different syntax.
Use the context menu on the same table, to get another script: "Script Table as | SELECT To | New Query Window". This will be a totally standard select list, with all your fields listed out. Copy the whole query and paste it in over the VALUES clause in your first query window. This will give you a complete INSERT ...
The syntax for creating a temp table with the select statement is as shown: SELECT column_list INTO #temporary_table_name FROM TABLE_NAME WHERE conditional_expression; We use the select statement followed by the name of the temporary table. The name of a temp table in SQL Server starts with a # sign.
Look at SELECT INTO. This will create a new table for you, which can be temporary if you want by prefixing the table name with a pound sign (#).
For example, you can do:
SELECT * INTO #YourTempTable FROM YourReportQuery
You can use select ... into ...
to create and populate a temp table and then query the temp table to return the result.
select * into #TempTable from YourTable select * from #TempTable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With