Check if a SQL table exists

后端 未结 9 2353
北海茫月
北海茫月 2020-12-01 06:30

What\'s the best way to check if a table exists in a Sql database in a database independant way?

I came up with:

   bool exists;
   const string sql         


        
9条回答
  •  甜味超标
    2020-12-01 06:53

    If you want to avoid try-catch solutions, I'm suggesting this method, using sys.tables

    private bool IsTableExisting(string table)
        {
            string command = $"select * from sys.tables";
            using (SqlConnection con = new SqlConnection(Constr))
            using (SqlCommand com = new SqlCommand(command, con))
            {
                SqlDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    if (reader.GetString(0).ToLower() == table.ToLower())
                        return true;
                }
                reader.Close();
            }
            return false;
        }
    

提交回复
热议问题