Drop table if exists ошибка

В ранних версиях SQL Server (до 2017) при удалении несуществующей таблицы (DROP TABLE t1;) вы получали сообщение об ошибке:
Не удалось удалить таблицу «t1″, так как она не существует или отсутствуют разрешения.»

В рамках интерактивного (чистого) SQL избежать возникновения ошибки в этом случае не получалось. Однако проблема легко решается процедурно (T-SQL):

IF object_id('t1') IS NOT NULL 
DROP TABLE t1;

Встроенная функция object_id возвращает идентификатор объекта, заданного именем, или же NULL, если такого имени не существует.
И вот в SQL Server 2017 появился оператор DROP TABLE IF EXISTS, который не вызывает ошибки, если удаляемой таблицы не существует, например:

DROP TABLE IF EXISTS t1;

Теперь предположим, что нам нужно удалить связанные таблицы. Рассмотрим следующий пример:

CREATE TABLE t1(id INT IDENTITY PRIMARY KEY);
CREATE TABLE t2(id INT IDENTITY PRIMARY KEY,
t1_id INT REFERENCES t1);
GO
INSERT INTO T1 DEFAULT VALUES;
GO 3 -- выполним предыдущий пакет (т.е. вставку) 3 раза

Проверим

SELECT * FROM t1;

id
1
2
3

INSERT INTO t2(t1_id) VALUES(1),(2);
SELECT * FROM t2;

id t1_id
1 1
2 2

Стандартное каскадное удаление

DROP TABLE t1 CASCADE;

работать не будет, т.к. оно еще не реализовано в SQL Server (но работает, например, в PostgreSQL), тогда как оператор

DROP TABLE t1;

вызовет следующую ошибку:
Невозможно удалить объект «t1», так как на него ссылается ограничение FOREIGN KEY.
Мы можем удалить связанные таблицы одним оператором, перечислив их через запятую (сначала подчиненную таблицу, а затем — главную):

DROP TABLE t2,t1;

Если указать таблицы в неправильном порядке, т.е. t1, t2, то при удалении t1 будет получена вышеприведенная ошибка, а потом будет удалена t2.
Если среди перечисленных таблиц (не обязательно две) могут быть отсутствующие, то тогда поможет новый оператор:

DROP TABLE IF EXISTS t2,t1;

Заметим, что оператор DROP … IF EXISTS может применяться и к другим объектам базы данных, например, представлениям и хранимым процедурам.
Возможно, что в следующих версиях SQL Server может появиться и оператор типа:

CREATE TABLE IF NOT EXISTS...

который будет создавать таблицу только в том случае, если такой не существует.

I have following block of code in MySql:

DROP TABLE IF EXISTS `account.info`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `account.info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL,
  `year_id` int(11) NOT NULL,
  `school_id` int(11) NOT NULL,
  PRIMARY KEY (`id`,`account_id`,`year_id`,`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7177 DEFAULT CHARSET=utf8;

Its giving me error on first line as:

ERROR 1103 (42000) at line 56: Incorrect table name 'account.info'

What is wrong in it?

Please help me.

asked Jan 15, 2014 at 11:20

C Sharper's user avatar

6

From http://dev.mysql.com/doc/refman/5.1/en/identifiers.html:
«Before MySQL 5.1.6, database and table names cannot contain “/”, “\”, “.”, or characters that are not permitted in file names.»

Which is why I gave this answer:

You can’t use dots in table names. Dots are used to separate database names and table names (and column names). You could try using `account`.`info` if your database name is account and the table name is info. If the table name is supposed to be account.info, you should change that to something else, like account_info. I don’t agree with some of the other answers: Quoting never hurts, if done properly.

Since 5.1.6 you can use whatever you please, as shown by @eggyal and others.

answered Jan 15, 2014 at 11:36

mrjink's user avatar

mrjinkmrjink

1,1311 gold badge17 silver badges28 bronze badges

1

As documented under Schema Object Names:

Before MySQL 5.1.6, database and table names cannot contain “/”, “\”, “.”, or characters that are not permitted in file names.

Incidentally, had you wanted to create a table called info within a database called account, then note that as documented under Identifier Qualifiers:

If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`.

answered Jan 15, 2014 at 11:27

eggyal's user avatar

eggyaleggyal

123k18 gold badges213 silver badges238 bronze badges

2

try this:

DROP TABLE IF EXISTS account.info;

dont use ` when using dots.

Or quote both db name and table name

DROP TABLE IF EXISTS `account`.`info`;

answered Jan 15, 2014 at 11:26

Positivity's user avatar

PositivityPositivity

5,4166 gold badges41 silver badges61 bronze badges

5

You seem to want to create and first drop a table in the database account with the name info. If so, do it like this:

DROP TABLE IF EXISTS `account`.`info`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `account`.`info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL,
  `year_id` int(11) NOT NULL,
  `school_id` int(11) NOT NULL,
  PRIMARY KEY (`id`,`account_id`,`year_id`,`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7177 DEFAULT CHARSET=utf8;

answered Jan 15, 2014 at 11:26

fancyPants's user avatar

fancyPantsfancyPants

50.8k33 gold badges90 silver badges97 bronze badges

3

You’re specifying a table called account.info and not a table called info in the account db. Quote each part separately:

DROP TABLE IF EXISTS `account`.`info`;

If you are trying to make a table called account.info then older versions of MySQL wont allow a . in a table name.

answered Jan 15, 2014 at 11:27

Jim's user avatar

JimJim

22.4k6 gold badges52 silver badges80 bronze badges

3

In PostgreSQL, the DROP command drops/deletes a specific database/table. However, Dropping or deleting a table that doesn’t exist in the targeted database will result in an error. To tackle such an error, the IF EXISTS parameter can be used with the DROP command.

Using practical examples, this post will show you the difference between the DROP and DROP IF EXISTS commands. So, let’s begin.

How to Drop a Table in PostgreSQL?

Use the DROP TABLE statement to drop the targeted Postgres table. DROP TABLE will have the following syntax:

DROP TABLE tab_name;

tab_name is a table to be dropped/deleted.

Example #1: How Does DROP Command Work in PostgreSQL?

Follow the below given stepwise instructions to drop a table in PostgreSQL:

Step # 1: Establish a Connection With the Selected Database

Firstly, open the SQL SHELL and specify the database name after the \c command to connect to a database of your choice:

\c example;

img

As the above snippet depicts, we are successfully connected to the selected database.

Step # 2: Check the Available Tables

Run the “\dt” command to see all the tables available in the “example” database”

\dt;

img

From the available tables, suppose we want to drop the bank_details table.

Step # 3: Drop the Selected Table
The below snippet explains how the DROP command works in PostgreSQL:

DROP TABLE bank_details;

On successful execution of the DROP TABLE command, you will get the following output:

img

The output demonstrates that the selected table has been dropped successfully.

Step # 4: Verify the Table’s Deletion

The \dt command followed by the table’s name provides the details about the selected table:

\dt bank_details;

img

The output proves that the bank_details table has been dropped from the example database. Let’s try to drop the selected table (i.e. bank_details) one more time and see how the DROP TABLE command works in such a situation:

DROP TABLE bank_details;

img

This time, we encountered an error saying that the desired table doesn’t exist.

Example #2: How Does DROP IF EXISTS Command Work in PostgreSQL?

The IF EXISTS is an option that checks the existence of a table. It can be seen from the above example that an error occurs when we tried to drop a table that doesn’t exist. We can avoid such an error using the IF EXISTS option.

Now, it’s time to learn the working of the DROP IF EXISTS command.

Step #1: Check the Available Tables

Let’s run the \dt command to get all the relations available in the example database:

\dt;

img

Let’s drop the “emp_data” table.

Step # 2: Drop the Selected Table

Run the DROP IF EXISTS command to drop the emp_data table:

DROP TABLE IF EXISTS emp_data;

img

So far so good, the selected table has been dropped successfully. Let’s try to drop it one more time:

DROP TABLE IF EXISTS emp_data;

img

DROP IF EXISTS retrieves a notice instead of throwing an error.

Conclusion

In PostgreSQL, the DROP command is used to drop/delete a specific database/table. However, Dropping or deleting a table that doesn’t exist in the targeted database will result in an error. To tackle such an error, the IF EXISTS parameter is used with the DROP command. The DROP command throws an error if a table to be dropped doesn’t exist, while “DROP IF EXISTS” shows a notice instead of throwing an error. This write-up explained the difference between DROP and “DROP IF EXISTS” with the help of examples.

Я добавляю эту таблицу:

CREATE TABLE contenttype (
        contenttypeid INT UNSIGNED NOT NULL AUTO_INCREMENT,
        class VARBINARY(50) NOT NULL,
        packageid INT UNSIGNED NOT NULL,
        canplace ENUM('0','1') NOT NULL DEFAULT '0',
        cansearch ENUM('0','1') NOT NULL DEFAULT '0',
        cantag ENUM('0','1') DEFAULT '0',
        canattach ENUM('0','1') DEFAULT '0',
        isaggregator ENUM('0', '1') NOT NULL DEFAULT '0',
        PRIMARY KEY (contenttypeid),
        UNIQUE KEY packageclass (packageid, class)
);

И я получаю таблицу 1050 «уже существует»

Но таблица НЕ существует. Любые идеи?

EDIT: подробности, потому что все, кажется, не верят мне:)

DESCRIBE contenttype

дает:

1146 — Таблица ‘gunzfact_vbforumdb.contenttype’ не существует

и

CREATE TABLE gunzfact_vbforumdb.contenttype(
contenttypeid INT UNSIGNED NOT NULL AUTO_INCREMENT ,
class VARBINARY( 50 ) NOT NULL ,
packageid INT UNSIGNED NOT NULL ,
canplace ENUM( '0', '1' ) NOT NULL DEFAULT '0',
cansearch ENUM( '0', '1' ) NOT NULL DEFAULT '0',
cantag ENUM( '0', '1' ) DEFAULT '0',
canattach ENUM( '0', '1' ) DEFAULT '0',
isaggregator ENUM( '0', '1' ) NOT NULL DEFAULT '0',
PRIMARY KEY ( contenttypeid ) ,

Урожайность:

1050 — Табл. ‘contenttype’ уже существует

  • Remove From My Forums
  • Question

  • I am on a simple quest to drop a table if it exists. Note that I have read other posts about doing this
    and they have not helped me

    When I run the following code to drop the INVOICE_BALANCES2 table it works if the table exists.

    if exists (

      select *  from [Core].[dbo].INVOICE_BALANCES2)

      drop table  [Core].[dbo].INVOICE_BALANCES2;

    However, if the table does not exist I get the error:

    ‘Invalid object name ‘Core.dbo.INVOICE_BALANCES2’

    ===================

    I’ve also found this code online though I don’t know what the ‘U’ is for:

    IF OBJECT_ID(INVOICE_BALANCES2, ‘U’) IS NOT NULL
    DROP TABLE INVOICE_BALANCES2;

    When I run this I get the error:

    Invalid column name ‘INVOICE_BALANCES2’

    Ok, so I put in a column name:

    IF OBJECT_ID(INVOICE_BALANCES2.cusno, ‘U’) IS NOT NULL
    DROP TABLE INVOICE_BALANCES2;

    When I run this I get the error:

    ‘The multi-part identifier «INVOICE_BALANCES2.cusno» could not be bound’

    Can someone help me to write simple statement to delete the INVOICE_BALANCES2 table if it exists and not return an error if it doesn’t exists?

    Thanks.

Answers

  • Hi JohnZofo

    If you would like to use

    IF OBJECT_ID(INVOICE_BALANCES2, 'U') IS NOT NULL
    DROP TABLE INVOICE_BALANCES2;

    Then know this is checking the database for the object id and if its in a database its an object. The
    object_id function takes two parameters both need to be in string format with single quotes.

    The first parameter is the table name and the second one is for the type of object, ‘U’ denoting User Created. So please try:

    IF OBJECT_ID('[TABLE NAME]', 'U') IS NOT NULL DROP TABLE [TABLE NAME];
    
    -- OR
    
    IF OBJECT_ID('[DATABASE NAME].dbo.[TABLE NAME]', 'U') IS NOT NULL DROP TABLE <TABLE NAME>;
    
    -- ALSO SEEN AS
    
    IF OBJECT_ID(N'tempdb.dbo.#temp', N'U') IS NOT NULL DROP TABLE tempdb.dbo.#temp;
    
    -- OR
    
    IF OBJECT_ID(N'tempdb..#temp', N'U') IS NOT NULL DROP TABLE dbo.#temp;

    P.S. You can find all objects in:

    SELECT * FROM SYS.OBJECTS
    • Edited by

      Friday, March 15, 2013 10:07 PM

    • Proposed as answer by
      Monica RiveraMicrosoft employee
      Friday, March 15, 2013 10:25 PM
    • Marked as answer by
      JohnZofo
      Monday, March 18, 2013 3:47 PM

  • If you just use «DROP TABLE  Invoices_Balances_2;»  you will get an error message («Cannot
    drop the table ‘hljkjk’, because it does not exist or you do not have permission.
    » ) which you can catch in a local
    variable. This is very old school. 

    DECLARE @error_flg INTEGER;
    DROP TABLE hljkjk
    SET @error_flg = @@ERROR;
    SELECT @error_flg; — 3701 if it was not there; 0 if it existed 


    —CELKO— Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

    • Marked as answer by
      JohnZofo
      Monday, March 18, 2013 3:47 PM

  • if exists(select 1 from core.sys.tables where [name]='INVOICE_BALANCES2')
    drop table core.dbo.INVOICE_BALANCES2;
    

    Josh

    • Marked as answer by
      JohnZofo
      Monday, March 18, 2013 3:47 PM

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Drone health ошибка
  • Driving stability bmw e60 ошибка
  • Dwservice exe ошибка приложения
  • Dwm exe системная ошибка 0xc0000005
  • Drm статус триколор ошибка 1002

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии