If you are working on some project where a database is needed, at some point in time, you need to analyze the Metadata of the database for performance issues or for other concerns.
In this blog, we will see some tricks to analyze the database metadata.
- Get all the database names.
- Get all the table names reside in the database.
- Get the header for all the tables.
- Get all the database names and size.
- Get all the table names with row count.
I am using C# code for getting this data and using MS SQL Server.
Get all the database names
Run this query on the master database.
First, I am writing an SQL query for this. Then, I’ll show you the C# code:
SELECT * FROM sys.databases
This gives you all the databases and additional info about those databases.
C# code for this query -
- public Void GetDatabaseList(string conString) {
- using(SqlConnection con = new SqlConnection(conString)) {
- con.Open();
- using(SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con)) {
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read()) {
- Console.WriteLine(rdr[0]);
- }
- }
- }
- }
For getting all the tables from a database. (Query on particular database)
SQL
- To get all the table names from a database
- SELECT name FROM sys.Tables
- To get only those tables which are having a particular column
- SELECT name
- FROM sys.tables
- WHERE Col_length(name, 'xyz') -- here xyz is your column name
C# Code
- public List < string > GetDatabaseList(string conString) {
- List < string > list = new List < string > ();
- using(SqlConnection con = new SqlConnection(conString)) {
- con.Open();
- using(SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con)) { //List<string> tables = new List<string>();
- DataTable dt = con.GetSchema("Tables");
- foreach(DataRow row in dt.Rows) {
- string tablename = (string) row[1] + "." + (string) row[2];
- list.Add(tablename);
- }
- }
- }
- return list;
- }
Get the header for all the tables
If you want to get the header of tables, the given code will help you. I don’t have any direct SQL query for this.
C# code
- private IEnumerable < string > GetColumnNames(string conStr, string tableName) {
- var result = new List < string > ();
- using(var sqlCon = new SqlConnection(conStr)) {
- sqlCon.Open();
- var sqlCmd = sqlCon.CreateCommand();
- sqlCmd.CommandText = "select * from " + tableName + " where 1=0"; // No data wanted, only schema
- sqlCmd.CommandType = CommandType.Text;
- var sqlDR = sqlCmd.ExecuteReader();
- var dataTable = sqlDR.GetSchemaTable();
- foreach(DataRow row in dataTable.Rows) result.Add(row.Field < string > ("ColumnName"));
- }
- return result;
- }
Here, we are fetching the schema of table and extracting the column names from that.
Get all the database names and size
SQL query
Join the conversation! Your thoughts help the community grow.