Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating temporary view from a temporary table in SQL Server

I have a temporary table and I would like to create a temporary view over this temporary table.

Is it possible?

In following example I would like #Top10Records to be a view instead of a table so that I get

select * into #Top10Records from (select top 10 * from #MytempTable) 
like image 439
Thunder Avatar asked Aug 25 '11 05:08

Thunder


People also ask

Can we create view on temporary table in SQL Server?

No, a view consists of a single SELECT statement. You cannot create or drop tables in a view.

How do I view a temporary table in SQL Server?

The name of a temporary table must start with a hash (#). Now, to see where this table exists; go to “Object Explorer -> Databases -> System Databases-> tempdb -> Temporary Tables”. You will see your temporary table name along with the identifier.

How do I create a temporary table from another table in SQL Server?

Create a Global Temporary Table in SQL Server. You can also create a global temporary table by placing double hash (##) before the temporary table name. The global temporary table will be available across different connections. 3 records will be inserted into the table.

Is a view a temporary table?

A temporary table is a base table that is not stored in the database but instead exists only while the database session in which it was created is active. At first glance, this may sound like a view, but views and temporary tables are rather different: A view exists only for a single query.


1 Answers

You can use a Common Table expression to do that:

WITH Top10Records  AS  (   select top 10 * from #MytempTable )  SELECT * FROM Top10Records  GO 
like image 143
DarylChymko Avatar answered Oct 15 '22 12:10

DarylChymko