Tuesday, March 27, 2012

Get a list of columns

I'm trying to get a list of columns from a table. Here is my code:

public List<string> GetColumns(string serverName, string dataBaseName, string tableName)

{

List<string> columns = new List<string>();

Server server = new Server(serverName);

server.ConnectionContext.LoginSecure = true;

server.ConnectionContext.Connect();

Database dataBase = new Database(server, dataBaseName);

Table table = new Table(dataBase, tableName);

foreach (Column column in table.Columns)

{

columns.Add(column.Name);

}

columns.Sort();

return columns;

}

The problem is that table.Columns.Count is 0. How do I get a list of columns in a table?

I got this working. Instead of getting a reference to each object individually:

Database dataBase = new Database(server, dataBaseName);

Table table = new Table(dataBase, tableName);

Then looping through the Columns collection of the table, I combined it all in one:

foreach (Column column in server.Database[dataBaseName].Tables[tableName].Columns)

This now gets me a list of all the columns in the table.

No comments:

Post a Comment