【问题标题】:How can I count the number of tables in C# [duplicate]如何计算 C# 中的表数 [重复]
【发布时间】:2015-08-12 10:01:12
【问题描述】:

如何编写代码以获取给定数据库中链接文本框的表数?我正在使用 Visual Studio 2013,对此我很陌生。我使用数据库服务器 ms sql。

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[0].ToString());
        }
        return TableNames;

    }

}

【问题讨论】:

  • Database_Name.information_schema.tables
  • 你的代码有什么问题?为什么schema.Rows.Count 不是您问题的答案?
  • 你能给我计数码吗
  • @sweatbar:是的,没问题:int tableCount = schema.Rows.Count;

标签: c# .net sql-server


【解决方案1】:

说实话,我不明白这个问题。您需要给定数据库中的表数。数据库由连接字符串指定。您已经有了返回所有表的 DataTable 的代码。

所以这是缺少的部分。由于connection.GetSchema("Tables") 也返回视图,如果你想计算两者,你准备好了:

DataTable schema = connection.GetSchema("Tables");
int tableAndViewCount = schema.Rows.Count;

如果您只想计算表并排除视图:

int tableCount = schema.AsEnumerable().Count(t => t.Field<string>("TABLE_TYPE") == "BASE TABLE");

【讨论】:

    【解决方案2】:

    使用以下查询获取表数,只需将该查询添加到您的应用程序中即可。

    SELECT COUNT(*) from information_schema.tables
    WHERE table_type = 'base table'
    

    【讨论】:

      【解决方案3】:

      试试这个查询

      从 sys.tables 中选择 *

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 2017-01-31
        • 1970-01-01
        • 2020-06-10
        • 2020-06-04
        相关资源
        最近更新 更多