2010-06-09 17 views

risposta

46

E 'semplice come questo:

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

dove _conn è un oggetto SqlConnection che è già stato collegato al database corretto.

+0

Un vantaggio di questo metodo rispetto ai metodi basati su query è che si ottengono metadati sulle tabelle in un DataTable, che non è semplice utilizzando le query. (Ma ho appena realizzato che hai bisogno solo dei nomi :)) – apoorv020

6

eseguire un comando SQL per:

SELECT name FROM sysobjects WHERE xtype = 'U' 
4

Vedere How to get a list of SQL Server databases per la sola andata:

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)); 
} 
+0

che non hanno nemmeno bisogno del proc memorizzato :) – slugster

+3

Si tratta di basi di dati, non le tabelle come richiesto, a destra ? –

4

Se si desidera ottenere tutti i nomi di tabelle da un database, è possibile fare qualcosa di simile;

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(); 
} 

ottenere tutti i database con l'altra risposta e creare una connessione a ciascuno e usare "GetAllTables" funzione per ottenere i nomi delle tabelle da quel db.

+0

Il tuo codice funziona. Ti sei perso per aprire e chiudere la connessione però. –

26

Solo un'altra soluzione:

public IList<string> ListTables() 
    { 
     List<string> tables = new List<string>(); 
     DataTable dt = _connection.GetSchema("Tables"); 
     foreach (DataRow row in dt.Rows) 
     { 
      string tablename = (string)row[2]; 
      tables.Add(tablename); 
     } 
     return tables; 
    } 
+6

hai visto la risposta di Slugster? –

+2

'(stringa) riga [2];' mi ha aiutato. grazie. –

3

Un altro modo, ma vale la pena menzionare: L'API contenuta in Microsoft.SqlServer.Smo.dll rende molto per l'accesso al database:

private IEnumerable<string> getAllTables() 
{ 
    var sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString); 
    var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection); 
    var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection); 
    var database = server.Databases[databaseName]; 
    foreach (Microsoft.SqlServer.Management.Smo.Table table in database.Tables) 
    { 
    yield return table.Name; 
    } 
} 

La cosa più bella è che l'oggetto Microsoft.SqlServer.Management.Smo.Table consente di eseguire tutti i tipi di operazioni, come cambiare schema, script, ecc ...

2

La mia versione di yonexbat risponde

public System.Collections.Generic.Dictionary<string, string> GetAllTables(System.Data.SqlClient.SqlConnection _connection) 
{ 
    if (_connection.State == System.Data.ConnectionState.Closed) 
     _connection.Open(); 
    System.Data.DataTable dt = _connection.GetSchema("Tables"); 
    System.Collections.Generic.Dictionary<string, string> tables = new System.Collections.Generic.Dictionary<string, string>(); 
    foreach (System.Data.DataRow row in dt.Rows) 
    { 
     if (row[3].ToString().Equals("BASE TABLE", StringComparison.OrdinalIgnoreCase)) //ignore views 
     { 
      string tableName = row[2].ToString(); 
      string schema = row[1].ToString(); 
      tables.Add(tableName, schema); 
     } 
    } 
    _connection.Close(); 
    return tables; 
} 
+1

Penso che dovrebbe essere 'if (row [3] .ToString(). Equals (" BASE TABLE ", StringComparison.OrdinalIgnoreCase))' – tic

+0

grazie tic l'ho corretto – irfandar

1

Grazie a Slugster per la sua risposta. Ecco una spiegazione estesa di come visualizzare un elenco delle tabelle in un database.

in forma asp.net aggiungere la seguente:

<div> 
    <asp:Button ID="GridViewTableListButton" runat="server" Text="List all Tables on server" 
     onclick="GridViewTableListButton_Click" /> 
    <asp:GridView ID="GridViewTableList" runat="server"> 
    </asp:GridView> 
</div> 

poi nel codice C# aggiungere dietro la seguente funzione:

protected void GridViewTableListButton_Click(object sender, EventArgs e) 
{ 
    objConn.Open(); 
    DataTable t = objConn.GetSchema("Tables"); 
    GridViewTableList.DataSource = t; 
    GridViewTableList.DataBind(); 
    objConn.Close(); 
} 

non dimenticando di aggiungere

using System.Data; 

e

SqlConnection objConn = new SqlConnection(); 

nella parte superiore della pagina/all'interno della classe genitore.

Con dentro il Load:

objConn.ConnectionString = ConfigurationManager.ConnectionStrings[connString].ConnectionString; 

connString è un file di classe (chiamato connectionClass.cs) che viene memorizzato nella cartella App_Code

public class connectionClass 
{ 
..... 
    public string connClass() 
    { 
     connString = "LocalSqlServer"; // LOCAL home PC Version 
    } 
} 

poi finalmente nel web.config

<add name="LocalSqlServer" connectionString="Data Source=MyPCsName\SQLEXPRESS;Initial Catalog=databasename;Integrated Security=True" providerName="System.Data.SqlClient"/> 

ad esempio

3

Sto usando questo ExtensionMethod per SqlConnection:

public static List<string> GetTableNames(this SqlConnection connection) 
{ 
    using(SqlConnection conn = connection) 
    { 
     if(conn.State == ConnectionState.Open) 
     { 
      return conn.GetSchema("Tables").AsEnumerable().Select(s => s[2].ToString()).ToList(); 
     }    
    } 
    //Add some error-handling instead ! 
    return new List<string>();   
} 
Problemi correlati