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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With