mercoledì 12 ottobre 2011

How To: Read Tables Definitions C# SqlServer

Sono più che convinto che ci siano parecchi modi per poter fare un analisi di che cosa contiene un Data Base. Ma giusto perchè ce ne sono tanti, ritengo utile condividere il mio.

Il prototipo è decisamente semplice, la logica prevede un accesso ad un DB sql server,
e una scansione di tutto quello che ci può resituire la stored "sp_tables" che è di sistema.
Ottenuto l'elenco delle tabelle, eseguo una scansione nested sulle colonne, in modo da recuperare tutte le altre informazioni ( diciamo quelle che mi servono ), tramite una seconda stored "sp_columns"

Partiamo quindi con la definizione delle tabella.

public class TableDef
{
public string TName { get; set; }
public string FName { get; set; }
public string FType { get; set; }
public string FSize { get; set; }
public string isNLL { get; set; }
}

public class TablesDef: List<TableDef>
{
}


Questo è il mio contenitore...

SqlConnection sc = new SqlConnection();
try
{
sc.ConnectionString = "connection string"

sc.Open();

SqlCommand c = new SqlCommand();
c.Connection = sc;
c.CommandText = "exec sp_tables";
c.CommandType = CommandType.Text;

SqlDataReader reader = c.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{

if (
(reader["Table_Owner"].ToString() != "INFORMATION_SCHEMA")
&&
(reader["Table_Owner"].ToString() != "sys"))
{
tNames.Add(reader["TABLE_NAME"].ToString());
}
}
}
reader.Close();

for (int i = 0; i < tNames.Count; i++)
{
td.AddRange(GetDataForTable(tNames[i], sc));
}
}
catch (Exception ex)
{
/*...*/
}
finally
{
if (sc.State == ConnectionState.Open)
{
sc.Close();
}
sc = null;
}


Questo è il mio processo di estrazione dei nomi delle tabelle, potrebbe essere discutibile la presenza di un DataReader ( ma in questo caso l'ho utilizzato per via della velocità ).

private TablesDef GetDataForTable(string tName, SqlConnection sc)
{

TablesDef td = new TablesDef();

SqlCommand c1 = new SqlCommand();

c1.CommandText = "exec sp_columns @table_name = '" + tName + "'";
c1.Connection = sc;
c1.CommandType = CommandType.Text;


SqlDataAdapter sda = new SqlDataAdapter(c1);

DataTable dt = new DataTable();

sda.Fill(dt);

if (dt!= null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TableDef tf = new TableDef();
tf.TName = tName;
tf.FName = dt.Rows[i]["COLUMN_NAME"].ToString();
tf.FType = dt.Rows[i]["TYPE_NAME"].ToString();
tf.FSize = dt.Rows[i]["PRECISION"].ToString();
tf.isNLL = dt.Rows[i]["IS_NULLABLE"].ToString();
td.Add(tf);

}
dt = null;
}

return td;
}


E questa è la modalità con cui estraggo le informazioni relative ai campi.

Al termine del processo ho tutto quello che mi serve in una lista che posso utilizzare per vari scopi.

Nessun commento: