12

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    You should iterate over the *rows* of `GetSchemaTable`, otherwise you're just getting the columns of the metadata. It's just a second table that describes the first one. – Alejandro Oct 16 '13 at 02:15
  • This is a duplicate of what seems like an infinite number of questions on SO and the web, and in MS documentation. Here is a good query to get you started on finding all the existing answers. I just took the title of your question and plugged it into google: http://bit.ly/GXswgz – Andrew Oct 16 '13 at 02:28

7 Answers7

28

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();
}
Szymon
  • 42,577
  • 16
  • 96
  • 114
23

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();
        }
Mark Kram
  • 5,672
  • 7
  • 51
  • 70
11
SELECT COLUMN_NAME
FROM   
INFORMATION_SCHEMA.COLUMNS 
WHERE   
TABLE_NAME = 'YourTable' 
t3chb0t
  • 16,340
  • 13
  • 78
  • 118
AnotherDeveloper
  • 1,242
  • 1
  • 15
  • 36
  • 3
    If you post code, XML or data samples, **PLEASE** highlight those lines in the text editor and click on the "code samples" button ( `{ }` ) on the editor toolbar to nicely format and syntax highlight it! – marc_s Oct 16 '13 at 05:14
  • I think this solution is easier to read and implement. – KWallace May 05 '22 at 23:48
3
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();
    }
M.Ali
  • 67,945
  • 13
  • 101
  • 127
3

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;
    }
Sierra
  • 71
  • 3
  • 2
    While this may solve the problem, you'd do well to highlight what you changed, added/removed to make the code work so that the OP can understand the root of the problem and anyone else coming in future won't have to search for what exactly you did. – Fabulous Aug 20 '18 at 17:34
  • On a resent edit, I just removed dead code used for a different solution mode, since it had become irrelevant. – Sierra Aug 20 '18 at 17:40
  • Any context you have, you should add it to your answer by editing it so that it can be found in one place. – Fabulous Aug 20 '18 at 17:41
  • As a help note to clarify any items in my code out side context of this question/response sample: ConnectionManager.ConnectionToSQL refers to the SQL Connection object for the SQL Server being used. And the InternalError is a public string object within the class that makes use of this code. Neither of this is relevant to the question at hand. I just want to prevent any irrelevant questions because of them.... – Sierra Aug 22 '18 at 20:46
1

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.
user2880576
  • 131
  • 1
  • 8
0
sp_columns - http://technet.microsoft.com/en-us/library/ms176077.aspx

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

jcwrequests
  • 1,132
  • 1
  • 7
  • 13