Cristian Lehuede Lyon
Cristian Lehuede Lyon

Reputation: 1947

Get column name from SQL Server

I'm trying to get the column names of a table I have stored in SQL Server 2008 R2.

I've literally tried everything but I can't seem to find how to do this.

Right now this is my code in C#

public string[] getColumnsName()
{
        List<string> listacolumnas=new List<string>();

        using (SqlConnection connection = new SqlConnection(Connection))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "SELECT TOP 0 * FROM Usuarios";
            connection.Open();

            using (var reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
                reader.Read();

                var table = reader.GetSchemaTable();

                foreach (DataColumn column in table.Columns)
                {
                    listacolumnas.Add(column.ColumnName);
                }
            }
        }
        return listacolumnas.ToArray();
    }

But this is returning me the following

<string>ColumnName</string>
<string>ColumnOrdinal</string>
<string>ColumnSize</string>
<string>NumericPrecision</string>
<string>NumericScale</string>
<string>IsUnique</string>
<string>IsKey</string>
<string>BaseServerName</string>
<string>BaseCatalogName</string>
<string>BaseColumnName</string>
<string>BaseSchemaName</string>
<string>BaseTableName</string>
<string>DataType</string>
<string>AllowDBNull</string>
<string>ProviderType</string>
<string>IsAliased</string>
<string>IsExpression</string>
<string>IsIdentity</string>
<string>IsAutoIncrement</string>
<string>IsRowVersion</string>
<string>IsHidden</string>
<string>IsLong</string>
<string>IsReadOnly</string>
<string>ProviderSpecificDataType</string>
<string>DataTypeName</string>
<string>XmlSchemaCollectionDatabase</string>
<string>XmlSchemaCollectionOwningSchema</string>
<string>XmlSchemaCollectionName</string>
<string>UdtAssemblyQualifiedName</string>
<string>NonVersionedProviderType</string>
<string>IsColumnSet</string>

Any ideas?

It shows the <string> tags as this is how my web service sends the data.

Upvotes: 12

Views: 65605

Answers (7)

Sierra
Sierra

Reputation: 71

The original post was close to the goal, Just some small changes and you got it. Here is my solution.

   public List<string> GetColumns(string tableName)
    {
        List<string> colList = new List<string>();
        DataTable dataTable = new DataTable();


        string cmdString = String.Format("SELECT TOP 0 * FROM {0}", tableName);

        if (ConnectionManager != null)
        {
            try
            {
                using (SqlDataAdapter dataContent = new SqlDataAdapter(cmdString, ConnectionManager.ConnectionToSQL))
                {
                    dataContent.Fill(dataTable);

                    foreach (DataColumn col in dataTable.Columns)
                    {
                       colList.Add(col.ColumnName);
                    }
                }                   
            }
            catch (Exception ex)
            {
                InternalError = ex.Message;
            }
        }


        return colList;
    }

Upvotes: 3

AnotherDeveloper
AnotherDeveloper

Reputation: 1272

SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'YourTable' 

Upvotes: 11

Szymon
Szymon

Reputation: 43023

You can use the query below to get the column names for your table. The query below gets all the columns for a user table of a given name:

select c.name from sys.columns c
inner join sys.tables t 
on t.object_id = c.object_id
and t.name = 'Usuarios' and t.type = 'U'

In your code, it will look like that:

public string[] getColumnsName()
{
    List<string> listacolumnas=new List<string>();
    using (SqlConnection connection = new SqlConnection(Connection))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "select c.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id and t.name = 'Usuarios' and t.type = 'U'";
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    listacolumnas.Add(reader.GetString(0));
                }
            }
        }
    return listacolumnas.ToArray();
}

Upvotes: 28

Mark Kram
Mark Kram

Reputation: 5832

I typically use the GetSchema method to retrieve Column specific information, this snippet will return the column names in a string List:

        using (SqlConnection conn = new SqlConnection("<ConnectionString>"))
        {
            string[] restrictions = new string[4] { null, null, "<TableName>", null };
            conn.Open();
            var columnList = conn.GetSchema("Columns", restrictions).AsEnumerable().Select(s => s.Field<String>("Column_Name")).ToList();
        }

Upvotes: 23

user2880576
user2880576

Reputation: 141

Currently, there are two ways I could think of doing this:

  • In pure SQL Server SQL you can use the views defined in INFORMATION_SCHEMA.COLUMNS. There, you would need to select the row for your table, matching on the column TABLE_NAME.
  • Since you are using C#, it's probably easier to obtain the names from the SqlDataReader instance that is returned by ExecuteReader. The class provides a property FieldCount, for the number of columns, and a method GetName(int), taking the column number as its argument and returning the name of the column.

Upvotes: 2

jcwrequests
jcwrequests

Reputation: 1130

sp_columns - http://technet.microsoft.com/en-us/library/ms176077.aspx

There are many built in stored procedures for this type of thing.

Upvotes: -1

M.Ali
M.Ali

Reputation: 69524

public string[] getColumnsName()
    {
        List<string> listacolumnas=new List<string>();
        using (SqlConnection connection = new SqlConnection(Connection))
        using (SqlCommand command = connection.CreateCommand())
        {
            command.CommandText = "select column_name from information_schema.columns where table_name = 'Usuarios'";
            connection.Open(;
            using (var reader = command.ExecuteReader(CommandBehavior.KeyInfo))
            {
                reader.Read();

                var table = reader.GetSchemaTable();
                foreach (DataColumn column in table.Columns)
                {
                    listacolumnas.Add(column.ColumnName);

                }
            }
        }
        return listacolumnas.ToArray();
    }

Upvotes: 3

Related Questions