Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve List of Tables from Specific Database on Server C#

Tags:

syntax

c#

sql

Looking for some C# examples that can retrieve the tables' names from a specific database on a server. I already have a valid connection string, just looking for the right way of adding the names of each table into List for later retrieval and manipulation.

like image 934
M4V3R1CK Avatar asked Jul 12 '11 21:07

M4V3R1CK


People also ask

How do I list all tables in a selected database?

MySQL SHOW TABLES command example To use the SHOW TABLES command, you need to log on to the MySQL server first. On opening the MySQL Command Line Client, enter your password. Select the specific database. Run the SHOW TABLES command to see all the tables in the database that has been selected.

How do I get a list of tables in SQL Server Management Studio?

First, enable Object Explorer Details going to View > Object Explorer Details or by pressing F7 buton. Now, select Tables element in your database in Object Explorer. List of tables with details will show in in the right pane in Object Explorer Details tab.


1 Answers

System.Data.SqlClient has what you need without a formal query on sys.Tables (though that's what it's using in the background). Use the GetSchema() method on the SqlConnection object and designate that you want the "Tables" and it will send you a DataTable object back with a row for each table. It sends back database name, table schema name, table name, and table type in each row (in that column order). The code would look like this:

public static List<string> GetTables(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        DataTable schema = connection.GetSchema("Tables");
        List<string> TableNames = new List<string>();
        foreach (DataRow row in schema.Rows)
        {
            TableNames.Add(row[2].ToString());
        }
        return TableNames;
    }
}
like image 78
Jacob Proffitt Avatar answered Oct 11 '22 12:10

Jacob Proffitt