Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a temporary table in SQL on the fly

Tags:

sql

sql-server

How can I create a temporary table without first creating the columns?

CREATE TABLE #Yaks (
YakID int,
YakName char(30) )

select name
from tempdb..sysobjects 
where name like '#yak%'

drop table #yaks

It is a pain to have to define the table first.

like image 533
eiu165 Avatar asked Sep 14 '12 04:09

eiu165


People also ask

How do you create a temporary table in SQL?

To create a Global Temporary Table, add the “##” symbol before the table name. Global Temporary Tables are visible to all connections and Dropped when the last connection referencing the table is closed. Global Table Name must have an Unique Table Name.

How do you make a fly table?

You want to run a SELECT query and save the result set into another table, but that table doesn't exist yet. Create the destination table first, or create it directly from the result of the SELECT.

Can we create temp table in view?

No, a view consists of a single SELECT statement. You cannot create or drop tables in a view. Maybe a common table expression (CTE) can solve your problem. CTEs are temporary result sets that are defined within the execution scope of a single statement and they can be used in views.

Can we create temp table in SQL Server?

So in such cases, SQL Server provides us with a feature called temporary tables which can be created at runtime and used to store the data temporarily. They can be used to create a workspace for processing the data inside stored procedure or functions. They can be used for complex joins.


1 Answers

Create a (temp) table with the same columns as another (no data copied):

select * into #TempTable
from MyTable
where 1=0

Note: Does not create any Foreign keys, indexes etc...

like image 79
Mitch Wheat Avatar answered Sep 21 '22 16:09

Mitch Wheat