Using GetSchemaTable() to retrieve only column names

后端 未结 4 859
无人共我
无人共我 2020-12-06 11:51

Is it possible to use GetSchemaTable() to retrieve only column names?

I have been trying to retrieve Column names (only) using this method, is it possi

相关标签:
4条回答
  • 2020-12-06 12:31

    You need to use ExecuteReader(CommandBehavior.SchemaOnly)):

    DataTable schema = null;
    using (var con = new SqlConnection(connection))
    {
        using (var schemaCommand = new SqlCommand("SELECT * FROM table", con))
        {
            con.Open();
            using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
            {
                schema = reader.GetSchemaTable();
            }
        }
    }
    

    SchemaOnly:

    The query returns column information only. When using SchemaOnly, the .NET Framework Data Provider for SQL Server precedes the statement being executed with SET FMTONLY ON.

    The column name is in the first column of every row. I don't think that it's possible to omit the other column informations like ColumnOrdinal,ColumnSize,NumericPrecision and so on since you cannot use reader.GetString but only reader.GetSchemaTable in this case.

    But your loop is incorrect if you only want the column names:

    foreach (DataRow col in schema.Rows)
    {
        Console.WriteLine("ColumnName={0}", col.Field<String>("ColumnName"));
    }
    
    0 讨论(0)
  • 2020-12-06 12:34

    This will give you all column names, you can place them in a string[] and do with them what you like.

    foreach(var columnName in DataTable.Columns)
    {
      Console.WriteLine(columnName);
    }
    
    0 讨论(0)
  • 2020-12-06 12:45

    Change your code to below if all you want is to display the column names. Your original code was trying to not only display column names, but also trying to display the actual data values as well.

    DataTable table = myReader.GetSchemaTable();
    
    foreach (DataRow myField in table.Rows)
    {
        foreach (DataColumn myProperty in table.Columns)
        {
            fileconnectiongrid.Rows.Add(myProperty.ToString());
        }
    }
    
    0 讨论(0)
  • 2020-12-06 12:46
    //Retrieve column schema into a DataTable.
    schemaTable = reader.GetSchemaTable();
    
    int index = schemaTable.Columns.IndexOf("ColumnName");
    DataColumn columnName = schemaTable.Columns[index];
    
    //For each field in the table...
    foreach (DataRow myField in schemaTable.Rows)
      {
        String columnNameValue = myField[columnName].ToString();
        Console.WriteLine("ColumnName " + columnNameValue);
      }
    
    0 讨论(0)
提交回复
热议问题