I need to alter one view and I want to introduce 2 temporary table before the SELECT.
Is this possible? And how can I do it?
ALTER VIEW myView AS SELECT * INTO #temporary1 SELECT * INTO #temporary2 SELECT * FROM #temporary1 UNION ALL SELECT * FROM #temporary1 DROP TABLE #temporary1 DROP TABLE #temporary2
When I attempt this it complains that ALTER VIEW must be the only statement in the batch.
How can I achieve this?
Creating views on temporary tables is not allowed.
If you are wondering why it is not required to drop the temp table at the end of the stored procedure, well, it is because when the stored procedure completes execution, it automatically drops the temp table when the connection/session is dropped which was executing it.
INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.
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. Each time you use the name of a view, its table is recreated from existing data. A temporary table exists for the entire database session in which it was created.
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.
Example (taken from here) - you can think of the SalesBySalesPerson
CTE as a temporary table:
CREATE VIEW vSalesStaffQuickStats AS WITH SalesBySalesPerson (SalesPersonID, NumberOfOrders, MostRecentOrderDate) AS ( SELECT SalesPersonID, COUNT(*), MAX(OrderDate) FROM Sales.SalesOrderHeader GROUP BY SalesPersonID ) SELECT E.EmployeeID, EmployeeOrders = OS.NumberOfOrders, EmployeeLastOrderDate = OS.MostRecentOrderDate, E.ManagerID, ManagerOrders = OM.NumberOfOrders, ManagerLastOrderDate = OM.MostRecentOrderDate FROM HumanResources.Employee AS E INNER JOIN SalesBySalesPerson AS OS ON E.EmployeeID = OS.SalesPersonID LEFT JOIN SalesBySalesPerson AS OM ON E.ManagerID = OM.SalesPersonID GO
Which are more performant, CTE or temporary tables?
You can achieve what you are trying to do, using a Stored Procedure
which returns a query result. Views
are not suitable / developed for operations like this one.
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