从服务器C#上的特定数据库中检索表的列表

寻找一些可以从服务器上的特定数据库中检索表名的C#示例。 我已经有了一个有效的连接字符串,只是寻找将每个表的名称添加到List中以便以后检索和操作的正确方法。

System.Data.SqlClient拥有您所需要的function,而无需在sys.Tables上进行正式查询(尽管这是它在后台使用的内容)。 在SqlConnection对象上使用GetSchema()方法并指定您想要“Tables”,它将向您发送一个DataTable对象,每个表都有一行。 它在每行中以该列顺序发送数据库名称,表模式名称,表名称和表类型。 代码如下所示:

 public static List GetTables(string connectionString) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); DataTable schema = connection.GetSchema("Tables"); List TableNames = new List(); foreach (DataRow row in schema.Rows) { TableNames.Add(row[2].ToString()); } return TableNames; } } 

对于SQL Server 2005及更高版本:

 using (SqlConnection connection = new SqlConnection(@"Data Source=(local);Integrated Security=True;Initial Catalog=DB_Name;")) { connection.Open(); using (SqlCommand command = connection.CreateCommand()) { command.CommandText = @"SELECT s.name, o.name FROM sys.objects o WITH(NOLOCK) JOIN sys.schemas s WITH(NOLOCK) ON o.schema_id = s.schema_id WHERE o.is_ms_shipped = 0 AND RTRIM(o.type) = 'U' ORDER BY s.name ASC, o.name ASC"; using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string schemaName = reader.GetString(0); string tableName = reader.GetString(1); // your code goes here... } } } } 

要从DB(SQlServer)获取所有用户定义的表,我们必须查询系统目录。

 SELECT Name from Sysobjects where xtype = 'u' 

此查询将返回DataBase中的所有用户定义的表

我认为这个SQL应该在数据库中返回一个包含tableNames的表:

 SELECT * FROM information_schema.tables 

我的解决方案:

  public void opencon() { if (conn == null) { conn = new SqlConnection(@"Your connection"); } if (conn.State == ConnectionState.Closed) { conn.Open(); } } public void Closecon() { if ((conn != null) && (conn.State == ConnectionState.Open)) { conn.Close(); } } public void GetTables(ComboBox cb) { chuoiketnoi(); DataTable schema = conn.GetSchema("Tables"); foreach (DataRow row in schema.Rows) { cb.Items.Add(row[2].ToString()); } dongketnoi(); }