How to delete a local temp table

  • I'm creating a local temp table for storing data like this:

    CREATE TABLE #fileexist ([File Exists] int, [File is a Directory] int, [Parent Directory Exists] int)

    However, I often get an error stating "There is already an object named '#fileexist' in the database". Therefor, I would like to do a IF EXISTS statement prior to creating the table to to drop it and suppress any error message, like this:

    IF EXISTS (SELECT whatever...)

    DROP TABLE #fileexist

    CREATE TABLE #fileexist ([File Exists] int, [File is a Directory] int, [Parent Directory Exists] int)

    Is there a way to do something like this? The actual table is virtual and only is visible to the current scope (doesn't show up in tempdb). Thanks for any advice you can offer!

  • IF OBJECT_ID('tempdb..#TableExist') IS NOT NULL

        TRUNCATE TABLE #TableExist

  • Thanks for your response. I'm getting some weird error messages. When I try to drop the table I get "Cannot drop the table '#fileexist', because it does not exist or you do not have permission" I am logged in as SA.

    When I try to create the table I still get the error "There is already an object named '#fileexist' in the database".

    So I'm getting contradicting messages. Any ideas? Thanks.

  • begin try

    drop table #test

    end try

    begin catch

    end catch

    create table #test(c1 int)

  • IF OBJECT_ID('TempDB..#FileExist') IS NOT NULL

    DROP TABLE #FileExist

    Make sure the name of the table is correct.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply