Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Columns of a Table by GetSchema() method

Tags:

c#

schema

ado.net

I want to get list of columns of a table using GetSchema method in ADO.Net, my code is:

var dtCols = con.GetSchema("Columns", new[] { "DBName", "TableName" });

And i get an empty DataTable, what is the problem?

like image 482
Navid Farhadi Avatar asked Jun 22 '12 16:06

Navid Farhadi


3 Answers

You must specify a parameter for the "owner" restriction.

var dtCols = con.GetSchema("Columns", new[] { "DBName", null, "TableName" });
like image 130
Matthew Avatar answered Nov 07 '22 06:11

Matthew


Could both of these answers be generalized a bit with:

dtCols = con.GetSchema("Columns", new[] {con.DataSource, null, "TableName"});

This is assuming that "TableName" is the name of the table that you want the schema for.

like image 32
Philip Sobolik Avatar answered Nov 07 '22 08:11

Philip Sobolik


This is my complete solution.

You just need to provide tableName and connectionString to this method:

// I took HUGE help from this Microsoft website: - AshishK
// https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.getschema?view=netframework-4.7.2#System_Data_SqlClient_SqlConnection_GetSchema_System_String_System_String___
public static List<string> GetAllColumnNamesOfATable(string tableName, string connectionString)
{
    var allColumnNames = new List<string>();

    using (var connection = new SqlConnection(connectionString))
    {
        // Connect to the database then retrieve the schema information.  
        connection.Open();

        // You can specify the Catalog, Schema, Table Name, Column Name to get the specified column(s).
        // You can use four restrictions for Column, so you should create a 4 members array.
        String[] columnRestrictions = new String[4];

        // For the array, 0-member represents Catalog; 1-member represents Schema;
        // 2-member represents Table Name; 3-member represents Column Name.
        // Now we specify the Table_Name and Column_Name of the columns what we want to get schema information.
        columnRestrictions[2] = tableName;

        DataTable allColumnsSchemaTable = connection.GetSchema("Columns", columnRestrictions);

        foreach (DataRow row in allColumnsSchemaTable.Rows)
        {
            var columnName = row.Field<string>("COLUMN_NAME");
                
            //You can capture other fields as well, like so:
            var dataType = row.Field<string>("DATA_TYPE");
            var characterMaxLength = row.Field<int?>("CHARACTER_MAXIMUM_LENGTH");

            allColumnNames.Add(columnName);
        }

        connection.Close();
    }

    return allColumnNames;
}
like image 28
Ash K Avatar answered Nov 07 '22 06:11

Ash K