Drop table if exists mysql ошибка

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,1321 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

122k18 gold badges210 silver badges236 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,3516 gold badges40 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.5k33 gold badges89 silver badges96 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.3k6 gold badges52 silver badges80 bronze badges

3

In MySQL, we can use the IF EXISTS clause of the DROP TABLE statement to check whether the table exists or not before dropping it.

Example

Here’s an example to demonstrate:

DROP TABLE IF EXISTS t1;

That statement drops a table called t1 if it exists.

When I ran that statement, the table already existed, and so it was dropped and I got the following message:

Query OK, 0 rows affected (0.00 sec)

When I ran the statement again (after it had already been dropped), I got the following message:

Query OK, 0 rows affected, 1 warning (0.00 sec)

So there was no error, but I did get a warning.

Let’s take a look at the warning:

SHOW WARNINGS;

Result:

+-------+------+-------------------------+
| Level | Code | Message                 |
+-------+------+-------------------------+
| Note  | 1051 | Unknown table 'test.t1' |
+-------+------+-------------------------+

The warning tells us that the table doesn’t exist, but it’s not an error.

Here’s what happens when we don’t use IF EXISTS:

DROP TABLE t1;

Result:

ERROR 1051 (42S02): Unknown table 'test.t1'

This time we get an error.

Also see 5 Ways to Check if a Table Exists in MySQL if you just want to check if a table exists without dropping it.

В этом учебном пособии вы узнаете, как использовать MySQL оператор DROP TABLE с синтаксисом и примерами.

Описание

MySQL оператор DROP TABLE позволяет стереть или удалить таблицу из базы данных MySQL.

Синтаксис

Простая форма синтаксиса для оператора DROP TABLE в MySQL:

DROP TABLE table_name;

Полный синтаксис для оператора MySQL DROP TABLE:

DROP [ TEMPORARY ] TABLE [ IF EXISTS ]
table_name1, table_name2, …
[ RESTRICT | CASCADE ];

Параметры или аргументы

TEMPORARY — необязательный. Он указывает, что только временные таблицы должны быть удалены с помощью оператора DROP TABLE.
table_name — имя таблицы для удаления из базы данных.
table_name1, table_name2 — таблицы для удаления из базы данных при удалении более одной таблицы в операторе DROP TABLE.
IF EXISTS — необязательный. Если указан, то оператор DROP TABLE не будет вызывать ошибку, если одна из таблиц не существует.
RESTRICT — необязательный. Он не влияет на оператор DROP TABLE, но включен в синтаксис, чтобы упростить перенос таблиц в разные базы данных.
CASCADE — необязательный. Он не влияет на оператор DROP TABLE, но включен в синтаксис, чтобы упростить перенос таблиц в разные базы данных.

Примечание

  • Если вы используете MySQL оператор DROP TABLE для удаления одной или нескольких таблиц, которые не существуют, база данных будет вызывать ошибку (если вы не укажете параметр IF EXISTS в операторе DROP TABLE).

Пример

Рассмотрим пример, показывающий, как удалить таблицу с помощью оператора MySQL DROP TABLE.

Удаление одной таблицы

Во-первых, давайте рассмотрим простой пример DROP TABLE, который показывает, как использовать оператор DROP TABLE для удаления одной таблицы в MySQL.
Например:

Этот пример DROP TABLE удалит таблицу, называемую customers.

Удаление нескольких таблиц

Рассмотрим пример, в котором мы хотим удалить несколько таблиц с помощью DROP TABLE:
Например:

DROP TABLE customers, suppliers;

В этом примере оператора DROP TABLE будут удалены две таблицы — customers и suppliers. Если мы опасаемся, что одна из таблиц не существует, и мы не хотим получить ошибку, то мы можем изменить наш оператор DROP TABLE следующим образом:

DROP TABLE IF EXISTS customers, suppliers;

Этот пример приведет к удалению таблиц customers и suppliers и не приведет к возникновению ошибки, если одна из таблиц не существует.

Удаление временной таблицы

Наконец, давайте рассмотрим пример, показывающий, как использовать оператор DROP TABLE для удаления временной таблицы.

DROP TEMPORARY TABLE IF EXISTS customers;

В этом примере DROP TABLE удалится только временная таблица с именем customers. Если бы существовала постоянная таблица customers, то этот оператор DROP TABLE не удалил бы ее, потому что задано TEMPORARY.

This article will be looking into how to drop a table if it exists in the database.

  • How to DROP Table IF EXISTS in MySQL
  • How to DROP Temporary Table IF EXISTS in MySQL

How to DROP Table IF EXISTS in MySQL

What all does a DROP TABLE statement does?

  • DROP TABLE statement will remove one or more table ( we must have the DROP privilege for each table).
  • Will remove the table definition and all table data. 
  • Will drop any triggers for the table.
  • If the table is partitioned, DROP TABLE will remove the partitions and all the data present in those partitions.

Syntax:- DROP TABLE [IF EXISTS] table_name [, table_name] …

Advertisements

IF EXISTS clause in the DROP statement is optional and has a role to play in its behaviour.

  • IF EXISTS clause present: When we run a DROP statement and if the given table does not exist, there will be no error occurring, but a warning message will be displayed.
  • IF EXISTS clause absent: When we run a DROP statement, and if the given table does not exist, the DROP statement will fail, displaying that an error has occurred for the non-existing tables which could not be deleted.

Let us look into an example. There is an existing table sale_details

Frequently Asked:

  • MySQL trigger example after insert
  • MySQL: Error 1264 Out of range value for a column [Solved]
  • MySQL Select where Count is greater than one [Solved]
  • MySQL: change column type to VARCHAR without losing data

Run the below query to verify the existence of the table.

SHOW TABLES LIKE "sale_details";

Output:-

figure 1.1

The result shows that table sale_details exist in the database.We will now be dropping this table, including IF EXISTS in the DROP statement. Observe the below statement and its output.

DROP TABLE IF EXISTS sale_details;

Action Output Message: DROP TABLE IF EXISTS sale_details 0 row(s) affected 0.023 sec

Again verify the table exists or not by running query “SHOW TABLES LIKE “sale_details”;” and observe the output.

figure 1.2

As we can see in the output, no tables are present in the result. Hence the table was dropped successfully. Since our table sale_details table does not exist, we will again run the DROP TABLE statement, including the IF EXISTS clause. Observe the below query.

DROP TABLE IF EXISTS sale_details;

Action Output Message: DROP TABLE IF EXISTS sale_details 0 row(s) affected, 1 warning(s): 1051 Unknown table ‘riti_sales_db.sale_details’ 0.0017 sec

figure 1.3

It shows a warning and not an error. Let us remove the IF EXISTS clause and watch the output.

DROP TABLE sale_details;

Action Output Message: DROP TABLE sale_details Error Code: 1051. Unknown table ‘riti_sales_db.sale_details’ 0.0013 sec

figure 1.4

This time it shows an error and not a warning.

How to DROP Temporary Table IF EXISTS in MySQL

A temporary table is a table that will store a temporary result set, which can be retrieved many times in a single session. DROP statement works the same way for temporary tables as well.

Syntax:- DROP TEMPORARY TABLE [IF EXISTS] table_name

We will create a temporary table sales_person_department from the sale_details table.

CREATE TEMPORARY TABLE sales_person_department
SELECT sale_person_name,sales_department FROM sale_details;

Action Output Message: CREATE TEMPORARY TABLE sales_person_department SELECT sale_person_name,sales_department FROM sale_details 12 row(s) affected Records: 12 Duplicates: 0 Warnings: 0 0.0023 sec.

The temporary table sales_person_department got created successfully. Now try dropping it using the IF EXISTS clause in DROP statement.

DROP TEMPORARY TABLE IF EXISTS sales_person_department;

Action Output Message:- DROP TEMPORARY TABLE IF EXISTS sales_person_department 0 row(s) affected 0.00046 sec.

figure 1.5

Table sales_person_department has been dropped successfully.

If we re-run the query to drop the temporary table sales_person_department, we will get a warning message.

DROP TEMPORARY TABLE IF EXISTS sales_person_department;

Action Output Message: DROP TEMPORARY TABLE IF EXISTS sales_person_department 0 row(s) affected, 1 warning(s): 1051 Unknown table ‘riti_sales_db.sales_person_department’ 0.00035 sec

figure 1.6
We hope this article provides a good understanding of DROP TABLE IF EXISTS in MySQL. Good Luck !!!

В ранних версиях 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...

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

Возможно, вам также будет интересно:

  • Driving stability bmw e60 ошибка бмв
  • Drivesafe 2 ошибка е07
  • Drivesafe 2 ошибка е06 что значит
  • Drivers aswrvrt sys ошибка 0хс0000098 как исправить
  • Driverpack ошибка установки драйвера

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

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