3

How can I know in C# the list of Tables in database.

The list of columns each tables has with complete specification like column one is Id and it has data type of int(50), etc

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
Shah
  • 1,604
  • 4
  • 20
  • 33
  • no. Just wondering how to do that – Shah Dec 18 '11 at 08:10
  • 2
    Try reading documentation first. – Sergio Tulentsev Dec 18 '11 at 08:14
  • 1
    Yes. Reading the documentatio nis not obtional. here is a whole chapter in there exactly about how to do that - in the sql server documentation that is. – TomTom Dec 18 '11 at 08:26
  • Related: *[Can I get name of all tables of SQL Server database in C# application?](http://stackoverflow.com/questions/3005095/can-i-get-name-of-all-tables-of-sql-server-database-in-c-sharp-application)* – slugster Dec 18 '11 at 08:28
  • you can get all table names from this link http://stackoverflow.com/questions/8464195/read-schema-name-table-name-and-column-name-from-a-sql-db-and-return-to-c-sharp/8464270#8464270 – Glory Raj Dec 18 '11 at 09:07

3 Answers3

8

Use the GetSchema method of the SqlConnection class:

DataTable t = _conn.GetSchema("Tables");

For more info read the MSDN article Retrieving Database Schema Information (ADO.NET). Note that this will get you the results without having to write or directly pass/execute any SQL.

slugster
  • 49,403
  • 14
  • 95
  • 145
2

Use the information schem views

http://msdn.microsoft.com/en-us/library/ms186778.aspx

Thy are the "standardized way to look at that and contrary to the sys tables quite guaranteed not to change (while the sys.* tables are an implementation detail).

TomTom
  • 61,059
  • 10
  • 88
  • 148
1

We have previously used SQL Server Management objects with good success. SMO allows you to interact with the SQL Server quite easily thorugh C#. You just need to reference some DLLs and use the object model provided by them. For example, to list the tables you can use the foreach to iterate over the Database.Tables -property.

Codeproject has an article which goes through the basics: http://www.codeproject.com/KB/database/SMODemo.aspx

Mikael Koskinen
  • 12,306
  • 5
  • 48
  • 63
  • Nice article it is. Sure it will help me. Being a beginner need some time to digest all the stuff – Shah Dec 18 '11 at 09:28