Can I get the names of all the tables of a SQL Server database in a C# application?

b1zrtrql  于 2023-04-19  发布在  SQL Server
关注(0)|答案(9)|浏览(165)

I want to get names of all the tables of SQL Server database in my C# application. Is it possible?

ozxc1zmp

ozxc1zmp1#

It is as simple as this:

DataTable t = _conn.GetSchema("Tables");

where _conn is a SqlConnection object that has already been connected to the correct database.

ne5o7dgx

ne5o7dgx2#

Just another solution:

public IList<string> ListTables()
    {
        List<string> tables = new List<string>();
        DataTable dt = _connection.GetSchema("Tables");
        foreach (DataRow row in dt.Rows)
        {
            string tablename = (string)row[2];
            tables.Add(tablename);
        }
        return tables;
    }
5gfr0r5j

5gfr0r5j3#

Run a sql command for:

SELECT name FROM sysobjects WHERE xtype = 'U'
vzgqcmou

vzgqcmou4#

I am using this ExtensionMethod for SqlConnection :

public static List<string> GetTableNames(this SqlConnection connection)
{
    using(SqlConnection conn = connection)
    {
        if(conn.State == ConnectionState.Open)
        {
            return conn.GetSchema("Tables").AsEnumerable().Select(s => s[2].ToString()).ToList();
        }            
    }
    //Add some error-handling instead !
    return new List<string>();        
}
gtlvzcf8

gtlvzcf85#

If you want to get all table names from a database you can do something like this ;

string[] GetAllTables(SqlConnection connection)
{
  List<string> result = new List<string>();
  SqlCommand cmd = new SqlCommand("SELECT name FROM sys.Tables", connection);
  System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
  while(reader.Read())
   result.Add(reader["name"].ToString());
  return result.ToArray();
}

Get all databases using the other response and create a connection to each and use function "GetAllTables" to get all table names from that db.

pu82cl6c

pu82cl6c6#

Another way but worth mentioning: The API contained in Microsoft.SqlServer.Smo.dll makes it very to access database:

private IEnumerable<string> getAllTables()
{
  var sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString);
  var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
  var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
  var database = server.Databases[databaseName];
  foreach (Microsoft.SqlServer.Management.Smo.Table table in database.Tables)
  {
    yield return table.Name;
  }
}

The coolest thing is that Microsoft.SqlServer.Management.Smo.Table object allows you to perform all kinds of operations, like changing schema, scripting, etc...

nuypyhwy

nuypyhwy7#

See How to get a list of SQL Server databases for one way:

System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234");
SqlCon.Open();

System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases";

System.Data.SqlClient.SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();

while(SqlDR.Read())
{
MessageBox.Show(SqlDR.GetString(0));
}
xbp102n0

xbp102n08#

My version of yonexbat answer

public System.Collections.Generic.Dictionary<string, string> GetAllTables(System.Data.SqlClient.SqlConnection _connection)
{
    if (_connection.State == System.Data.ConnectionState.Closed)
        _connection.Open();
    System.Data.DataTable dt = _connection.GetSchema("Tables");
    System.Collections.Generic.Dictionary<string, string> tables = new System.Collections.Generic.Dictionary<string, string>();
    foreach (System.Data.DataRow row in dt.Rows)
    {
        if (row[3].ToString().Equals("BASE TABLE", StringComparison.OrdinalIgnoreCase)) //ignore views
        {
            string tableName = row[2].ToString();
            string schema = row[1].ToString();
            tables.Add(tableName, schema);
        }
    }
    _connection.Close();
    return tables;
}
moiiocjp

moiiocjp9#

Thanks to Slugster for his answer. Here is an expanded explanation of how to view a list of the tables in an database.

in an asp.net form add the following:

<div>
    <asp:Button ID="GridViewTableListButton" runat="server" Text="List all Tables on server" 
        onclick="GridViewTableListButton_Click"  />
    <asp:GridView ID="GridViewTableList" runat="server">
    </asp:GridView>
</div>

then in C# code behind add the following function:

protected void GridViewTableListButton_Click(object sender, EventArgs e)
{
    objConn.Open();
    DataTable t = objConn.GetSchema("Tables");
    GridViewTableList.DataSource = t;
    GridViewTableList.DataBind();
    objConn.Close();
}

not forgetting to add

using System.Data;

and

SqlConnection objConn = new SqlConnection();

at the top of you page / inside your parent class.

With inside your Page_Load:

objConn.ConnectionString = ConfigurationManager.ConnectionStrings[connString].ConnectionString;

connString is a class file (called connectionClass.cs) that is stored in the App_Code folder

public class connectionClass
{
.....
    public string connClass()
    {
        connString = "LocalSqlServer"; // LOCAL home PC Version
    }
}

then finally in web.config

<add name="LocalSqlServer" connectionString="Data Source=MyPCsName\SQLEXPRESS;Initial Catalog=databasename;Integrated Security=True" providerName="System.Data.SqlClient"/>

for example

相关问题