简体   繁体   中英

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)

You can use a Common Table expression to do that:

WITH Top10Records  AS 
( 
 select top 10 * from #MytempTable
) 
SELECT * FROM Top10Records 
GO

Unfortunately, SQL Server doesn't support this:

Msg 4103, Level 15, State 1, Line 3
"#someView": Temporary views are not allowed.
Msg 4508, Level 16, State 1, Line 6
Views or functions are not allowed on temporary tables. Table names that begin with '#' denote temporary tables.

SQL Server does not support temporary views as such and as stated above by Daryl, a Common Table Expression is probably the way to go. However, one limitation of a CTE is that it can't be used across multiple queries in a batch. You can however create a standard view, use it as required then simply drop it at the end of the batch/transaction. (I know the OP question is whether or not you can create a temporary view, but this may also potentially apply - it requires a schema change, but a transient one for all intents and purposes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM