I'm working on a database migration where I need to drop all the tables in a specific schema and then run another script to recreate them from another database.
I'm running into issues with trying to delete specific tables in the proper order.
Is there a SQL query that will order the tables in the correct order so they can be dropped properly?
Here is the code I am trying so far, but the tables are not in the proper order:
private void CreateDropStatementsAndRun(string schema)
{
string sql = string.Format(@"SELECT table_name
FROM information_schema.tables
WHERE table_schema = '{0}';", schema);
var connectionString = ConfigurationManager.ConnectionStrings["TARGET_DefaultConnection"];
StringBuilder sb = new StringBuilder();
var listOfTables = new List<string>();
using (SqlConnection conn = new SqlConnection(connectionString.ConnectionString))
{
conn.Open();
using (var command = new SqlCommand(sql, conn))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
listOfTables.Add(reader.GetString(0));
}
}
}
foreach (var item in listOfTables)
{
sb.AppendFormat("alter table {0}.{1} nocheck constraint all;", schema, item).AppendLine();
sb.AppendFormat("DROP TABLE IF EXISTS {0}.{1};", schema, item).AppendLine();
}
using (var cmd = new SqlCommand(sb.ToString(), conn))
{
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}