Monday, March 1, 2010

how to get a list of tables in a database using C#

Unsurprisingly, if a table doesn't exist in a database, you can't use a select query to determine whether it exists. But using GetSchema() with no parameters, you can obtain a schema table, which is essentially a list of tables you can specify to get more specific schema information. In this case, I wanted to get a list of tables in the database. After transforming the results into a list of strings, I could then safely search the list to determine whether it exists.


SqlConnection con =
new SqlConnection("connection_string");
con.Open();
DataTable tbl =
con.GetSchema("Tables");


Schema and metadata retrieval using ADO.NET

this also works, depending on whether you need these extra parameters, but its a big uglier:


DataTable tables =
con.GetOleDbSchemaTable
(OleDbSchemaGuid.Tables,
new object[]{null,null,null,"TABLE"});


Get all table names

No comments: