tags:

views:

136

answers:

4

I want to get name of all table of SQL Server database in my C# application. Is It possible? Plz tell me Solution.

+3  A: 

Run a sql command for:

SELECT name FROM sysobjects WHERE xtype = 'U'
dnolan
+1  A: 

See How to get a list of SQL Server databases for one way:

System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection("server=192.168.0.1;uid=sa;pwd=1234");
SqlCon.Open();

System.Data.SqlClient.SqlCommand SqlCom = new System.Data.SqlClient.SqlCommand();
SqlCom.Connection = SqlCon;
SqlCom.CommandType = CommandType.StoredProcedure;
SqlCom.CommandText = "sp_databases";

System.Data.SqlClient.SqlDataReader SqlDR;
SqlDR = SqlCom.ExecuteReader();

while(SqlDR.Read())
{
MessageBox.Show(SqlDR.GetString(0));
}
Galwegian
You don't even need the stored proc :)
slugster
+4  A: 

It is as simple as this:

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

where _conn is a SqlConnection object that has already been connected to the correct database.

slugster
AN advantage of this method over query-based methods is that you get metadata about the tables in a DataTable, which is not simple using queries. (But I just realized you need only names :) )
apoorv020
+1  A: 

If you want to get all table names from a database you can you something like this

string[] GetAllTables(SqlConnection connection)
{
  List<string> result = new List<string>();
  SqlCommand cmd = new SqlCommand("SELECT name FROM sys.Tables", connection);
  System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
  while(reader.Read())
   result.Add(reader["name"].ToString());
  return result.ToArray();
}

Get all databases using using the other response and create a connection to each and use function "GetAllTables" to get all table names from that db.

Manu