Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2008

List SQL Server table column name as rows

0.00/5 (No votes)
3 May 2012CPOL 11.6K  
This is an alternative for List SQL Server table column name as rows

A more database-agnostic way to get information about the columns of a table in .NET is to use the GetSchemaTable method of an IDataReader. Simply perform ExecuteReader on an SQL statement like

SQL
SELECT * FROM source WHERE 0=1

(being sure to protect against SQL injection of course) and iterate the Rows in the resultant DataTable. The 0=1 ensures that we don't waste bandwidth transferring data needlessly. You can (and should) Close the IDataReader as soon as you have the DataTable.

I have found that each ADO.NET provider uses a slightly different order of the columns and some have more columns than others, but the only ones I'm interested in are: ColumnName, DataType, ProviderType, ColumnSize, and AllowDBNull. ProviderType needs to be parsed into an appropriate enumeration (e.g. System.Data.SqlDbType when using SQL Server) to get a meaningful value.

An additional benefit of this technique is that you can list out the columns of a view or ad hoc SQL as well, not just tables.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)