Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if table exists in a migration?

This is as close as I've got...

public static class Helpers
{
    public static bool TableExists(this MigrationBuilder builder, string tableName)
    {
        bool exists = builder.Sql($@"SELECT 1 FROM sys.tables AS T
                     INNER JOIN sys.schemas AS S ON T.schema_id = S.schema_id
                     WHERE S.Name = 'SchemaName' AND T.Name = '{tableName}'");

        return exists;
    }

}

But how does one get a result form the SQL call?

like image 880
Ian Warburton Avatar asked Oct 02 '17 18:10

Ian Warburton


People also ask

How to check if a table exists in sql?

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 to check if table exist in Laravel?

Change your 'table_name' value. If you get one row output, it means the table exists.

Do migrations create tables?

Typically, migrations will use this facade to create and modify database tables and columns.


1 Answers

It's not a perfect solution, but you could use an IF in SQL:

builder.Sql(@"
    IF (EXISTS(SELECT * 
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'MySchema'
        AND  TABLE_NAME = 'TableName'))
    BEGIN
        --DO SOMETHING
    END
");
like image 107
Whopperle Avatar answered Sep 19 '22 11:09

Whopperle