How to check if table exists in a migration?

Viewed 10598

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?

2 Answers

Here is one solution...

public override void Up()
{
    if (!Exists("dbo.MyTable"))
    {
        ... do something
    }
}

private static bool Exists(string tableName)
{
    using (var context = new DbContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        var count = context.Database.SqlQuery<int>("SELECT COUNT(OBJECT_ID(@p0, 'U'))", tableName);

        return count.Any() && count.First() > 0;
    }
}

This query runs immediately rather than being defered like other DbMigration commands are - but that's why it works. The result is known straight away so that other commands can be queued (or not queued) as required.

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
");
Related