【问题标题】:getting Schema of one Table in C#在 C# 中获取一个表的架构
【发布时间】:2012-06-25 12:41:07
【问题描述】:

我想在 SQL SErver 中获取名为“Petro”的表的架构 初始化connectionString后,我使用这个代码

conn.open();
conn.getSchema("Tables");

但它返回所有表的架构。我只想要 Petro 模式。我该怎么办?

【问题讨论】:

标签: c# sql


【解决方案1】:

您可以通过以下方式检索架构:

            string sql = "select * from Petro WHERE 1 = 0";
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader reader = cmd.ExecuteReader();
            DataTable schema = reader.GetSchemaTable();

【讨论】:

  • 您真的想在 Petro 上选择 * 只是为了获取架构吗?看起来 cmd.ExecuteReader 为此增加了很多不必要的开销。
  • 由于OP在问题中除了表名之外没有提到任何列名,我已经在此基础上回答了......
  • 不愿承认(6 年后),但这是唯一对我有用的代码...
【解决方案2】:
string[] restrictions = new string[4];
restrictions[2] = "Petro";
DataTable table = conn.GetSchema("Tables",restrictions);

查看这里了解更多信息:MSDN: Working with the GetSchema Methods

编辑:使用 GetSchema 而不是 getSchema

【讨论】:

  • 此代码将仅返回 1 行带有表名的行。如果需要获取完整的表模式(所有列及其类型),代码应如下:conn.GetSchema("Columns", restrictions);
  • 这只返回表属性而不是表字段。
【解决方案3】:

SQL Server 解决方案:

有一个名为sp_columns 的存储过程。当您使用表名作为参数运行该过程时,它将仅返回该表的架构。

【讨论】:

    猜你喜欢
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2012-02-04
    • 2018-11-25
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多