Reputation: 11
Question says it all really, I just want the all column names from a table, I'm looking for as basic way to do this as possible.
Upvotes: 1
Views: 3157
Reputation: 20302
This should do what you want.
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();
}
Get column name from SQL Server
Upvotes: 0
Reputation: 12577
If you run the following SQL you'll get an empty rowset. From which you can interpret the column names by using a SqlCommand
and DataReader
.
using (var conn = new SqlConnection("your_conn_string"))
{
var command = new SqlCommand("select * from [dbo].[tableName] where 1 = 2");
conn.Open();
using(var dr = command.ExecuteReader())
{
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
{
columns.Add(reader.GetName(i));
}
}
}
Upvotes: 4
Reputation: 1269493
That depends entirely on the database. Almost all databases have some sort of metadata about the database. Most implement some version of the information_schema
method.
For instance, a common way to get information about columns is:
select column_name
from information_schema.columns
where table_name = ? and table_schema = ?;
?
are place-holders for the table name and schema.
Upvotes: 0