Hi Im creating a Temp table and inserting data to the Table. Im going to use the Temp table to Join it to the specific User.
CREATE TABLE #MyTempTable
(
UsersId int,
ValautionCount int
)
SELECT
U.UserId,
COUNT(*) AS ValautionCount
INTO #MyTempTable
FROM
Users U
Right JOIN Valuation V ON V.ValuationUser = U.UserId
GROUP BY
U.UserId
DROP TABLE #MyTempTable
When I run this query I get this error : There is already an object named '#Temp' in the database.
But when I run this query DROP TABLE #MyTempTable
I get this error: Cannot drop the table '#Temp', because it does not exist or you do not have permission.
Im using SQL 2012
The reason SQL won't let you drop a table in this situation is because the allocation pages/extent chain appears to be damaged or cross-linked in some way. So SQL Server thinks that there is actually data from other tables in pages/extents belonging to the problem object.
Using the DROP TABLE command on a temporary table, as with any table, will delete the table and remove all data. In an SQL server, when you create a temporary table, you need to use the # in front of the name of the table when dropping it, as this indicates the temporary table.
In SQL Server, we can use the OBJECT_ID function to get the table name of the temporary table, and if the table is found, we can use the DROP TABLE statement to drop the temp table in sql. Another method we learned is to use the DROP TABLE IF EXISTS statement.
#1519212. #temp tables are available ONLY to the session that created it and are dropped when the session is closed. ##temp tables (global) are available to ALL sessions, but are still dropped when the session that created it is closed and all other references to them are closed.
SELECT ... INTO ... statement itself create the #Temp table. Does not need CREATE TABLE statement here. Remove "CREATE TABLE" statement and try.
You already have an entity by name "Temp" in your database. And you are not able to drop that entity because of access permissions.
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