Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check table exists

Tags:

php

mysql

dao

yii2

I need to check if a table exists in a database. I currently develop using Yii2.

My case is a bit different from this question because the table to be checked is not (and can not be) a model.

I have tried (new \yii\db\Query())->select('*')->from($mysticTable)->exists());

The above throws a yii\db\Exception because, according to question linked above, the yii\db\Query() class tries to ->queryScalar() when asked if ->exists(). Invariably, this method checks if the result-set exists.

How do I check if a table exists?

like image 383
Igbanam Avatar asked Jul 28 '15 08:07

Igbanam


People also ask

How do I check if a table exists?

To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.

How do you check a table exists in SQL Server?

IF EXISTS( SELECT * FROM INFORMATION_SCHEMA. TABLES WHERE TABLE_NAME = 'Album' ) SELECT 'found' AS search_result ELSE SELECT 'not found' AS search_result; The query will return the word 'found' if the table 'Album' exists in our database.

How do you check a table exists in Oracle?

Answers. OK, please proceed to do so. declare cnt number; begin select count(*) into cnt from user_tables where table_name = 'EMP1'; if cnt>0 then execute immediate 'truncate table emp1'; DBMS_OUTPUT. PUT_LINE('Truncated the table'); else execute immediate 'create table emp1 as select * from emp'; DBMS_OUTPUT.

How do you check if a table does not exist in SQL?

Another way to check whether a table already exists is to query the information_schema. tables view: IF EXISTS ( SELECT * FROM information_schema. tables WHERE table_schema = 'dbo' AND table_name = 't1') DROP TABLE dbo.


1 Answers

For Yii2 you can use:

$tableSchema = Yii::$app->db->schema->getTableSchema('tableName');

If the table does not exist, it will return null, so you can check returned value for being null:

if ($tableSchema === null) {
    // Table does not exist
}

You can find this method in official docs here.

like image 127
arogachev Avatar answered Sep 20 '22 13:09

arogachev