Another option using pure C # /. NET code: First, a helper method is used that returns a simple list of column names. Using a DataTable to store schema schema data means that other information can also be retrieved for each column, fx. if it is an AutoIncreament column, etc.
private IEnumerable<string> GetColumnNames(string conStr, string tableName) { var result = new List<string>(); using (var sqlCon = new SqlConnection(conStr)) { sqlCon.Open(); var sqlCmd = sqlCon.CreateCommand(); sqlCmd.CommandText = "select * from " + tableName + " where 1=0";
The method can be called the following:
var sortedNames = GetColumnNames("Data Source=localhost;Initial Catalog=OF2E;Integrated Security=SSPI", "Articles").OrderBy(x => x); foreach (var columnName in sortedNames) Console.WriteLine(columnName);
Niels Peter Gibe
source share