DROP IF EXISTS VS DROP?

前端 未结 5 455
南方客
南方客 2020-12-07 09:29

Can someone tell me if there is any difference between

DROP IF EXISTS [TABLE_NAME]
DROP [TABLE_NAME]

I am askin

相关标签:
5条回答
  • 2020-12-07 09:45
    DROP TABLE IF EXISTS [table_name]
    

    it first checks if the table exists, if it does it deletes the table while

    DROP TABLE [table_name]
    

    it deletes without checking, so if it doesn't exist it exits with an error

    0 讨论(0)
  • 2020-12-07 09:46

    It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

    From SQL Server 2016+ you can use

    DROP TABLE IF EXISTS dbo.Table
    

    For SQL Server <2016 what I do is the following for a permanent table

    IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL 
      DROP TABLE dbo.Table; 
    

    Or this, for a temporary table

    IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
      DROP TABLE #T; 
    
    0 讨论(0)
  • 2020-12-07 09:56

    You forgot the table in your syntax:

    drop table [table_name]
    

    which drops a table.

    Using

    drop table if exists [table_name]
    

    checks if the table exists before dropping it.
    If it exists, it gets dropped.
    If not, no error will be thrown and no action be taken.

    0 讨论(0)
  • 2020-12-07 09:58

    Standard SQL syntax is

    DROP TABLE table_name;
    

    IF EXISTS is not standard; different platforms might support it with different syntax, or not support it at all. In PostgreSQL, the syntax is

    DROP TABLE IF EXISTS table_name;
    

    The first one will throw an error if the table doesn't exist, or if other database objects depend on it. Most often, the other database objects will be foreign key references, but there may be others, too. (Views, for example.) The second will not throw an error if the table doesn't exist, but it will still throw an error if other database objects depend on it.

    To drop a table, and all the other objects that depend on it, use one of these.

    DROP TABLE table_name CASCADE;
    DROP TABLE IF EXISTS table_name CASCADE;
    

    Use CASCADE with great care.

    0 讨论(0)
  • 2020-12-07 09:58

    If no table with such name exists, DROP fails with error while DROP IF EXISTS just does nothing.

    This is useful if you create/modifi your database with a script; this way you do not have to ensure manually that previous versions of the table are deleted. You just do a DROP IF EXISTS and forget about it.

    Of course, your current DB engine may not support this option, it is hard to tell more about the error with the information you provide.

    0 讨论(0)
提交回复
热议问题