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 t开发者_运维知识库able 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).
精彩评论