Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't drop temp table SQL

Tags:

sql

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

like image 334
Johan de Klerk Avatar asked Nov 05 '12 06:11

Johan de Klerk


People also ask

Why can't I drop a table in SQL?

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.

Can we drop temporary table in SQL?

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.

How do I drop a #tmp table in SQL?

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.

What is #table and ## table in SQL?

#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.


2 Answers

SELECT ... INTO ... statement itself create the #Temp table. Does not need CREATE TABLE statement here. Remove "CREATE TABLE" statement and try.

like image 109
Prasanna Avatar answered Sep 28 '22 02:09

Prasanna


You already have an entity by name "Temp" in your database. And you are not able to drop that entity because of access permissions.

like image 34
Vivek Avatar answered Sep 28 '22 02:09

Vivek