Dynamically displaying fields from a database table

Is there a way to query the database for table schema information? I am only interested in getting a list of column names and whether they are primary keys; Is it possible? I don't care about the type, just his name and whether he is the primary key.

Example table:

Table Organism
{
   primary: int ID;
   int Kingdom;
   int Phylum;
   int Class;
   int Genus;
   int Species;
   nvarchar(50) Name;
}

Usage example:

List<Tuple<string, bool>> t = ReadTable("Organism");
t.ForEach(x => Console.WriteLine(x.Item2 ? x.Item2 + ": " + x.Item1 : x.Item1));

Output Example:

True ID
Kingdom
Phylum
Class
Genus
Species
Name

I am using C # 4.0 and SQL Server 2008 R2. I think this should be possible using system tables, but I don't know how to do this.

+3
source share
2 answers
select col.*
from sys.columns col
join sys.tables tab on col.object_id = tab.object_id
where tab.name = @tabName
order by col.column_id

System views contain a lot of data and are easy to use.

+2
source

You can get field names with such a hacker request

select * from Organism where 1=2

" " , , :

SELECT * FROM databaseName.INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
Where TABLE_NAME='Organism' 
+1

All Articles