Controleer of een entiteit bestaat (MySQL)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

Mischien de elegantste manier om te verifiëren of een bepaalde tabel bestaat:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = "database name"
AND table_name = "table name";

Voorbeeld 1:

select count(*) from information_schema.tables
where table_schema='koolborstels'
and table_name='term_data_bk01';

Resultaat:

+----------+--------------+----------------+
| count(*) | table_schema | table_name     |
+----------+--------------+----------------+
|        1 | koolborstels | term_data_bk01 |
+----------+--------------+----------------+

Voorbeeld 2:

select count(*) from information_schema.tables
where table_schema='koolborstels'
and table_name='term_data_bk0fdsfdsfdsfds1';

Resultaat:

+----------+--------------+----------------+
| count(*) | table_schema | table_name     |
+----------+--------------+----------------+
|        0 | koolborstels | term_data_bk0fdsfdsfdsfds1 |
+----------+--------------+----------------+

Dit genereert géén foutmelding.

Bronnen