Know Your Database Metadata With C# Code

In this blog, we will see some tricks to analyze the database metadata.

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.

  1. Get all the database names.
  2. Get all the table names reside in the database.
  3. Get the header for all the tables.
  4. Get all the database names and size.
  5. 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 -

  1. public Void GetDatabaseList(string conString) {  
  2.     using(SqlConnection con = new SqlConnection(conString)) {  
  3.         con.Open();  
  4.         using(SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con)) {  
  5.             SqlDataReader rdr = cmd.ExecuteReader();  
  6.             while (rdr.Read()) {  
  7.                 Console.WriteLine(rdr[0]);  
  8.             }  
  9.         }  
  10.     }  
Get all the table names residing in the database

For getting all the tables from a database. (Query on particular database)

SQL

  1. To get all the table names from a database
    1. SELECT name FROM sys.Tables  
  2. To get only those tables which are having a particular column
    1. SELECT name   
    2. FROM   sys.tables   
    3. WHERE  Col_length(name'xyz'-- here xyz is your column name   

C# Code

  1. public List < string > GetDatabaseList(string conString) {  
  2.     List < string > list = new List < string > ();  
  3.     using(SqlConnection con = new SqlConnection(conString)) {  
  4.         con.Open();  
  5.         using(SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con)) { //List<string> tables = new List<string>();  
  6.             DataTable dt = con.GetSchema("Tables");  
  7.             foreach(DataRow row in dt.Rows) {  
  8.                 string tablename = (string) row[1] + "." + (string) row[2];  
  9.                 list.Add(tablename);  
  10.             }  
  11.         }  
  12.     }  
  13.     return list;  
  14. }  

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

  1. private IEnumerable < string > GetColumnNames(string conStr, string tableName) {  
  2.     var result = new List < string > ();  
  3.     using(var sqlCon = new SqlConnection(conStr)) {  
  4.         sqlCon.Open();  
  5.         var sqlCmd = sqlCon.CreateCommand();  
  6.         sqlCmd.CommandText = "select * from " + tableName + " where 1=0"// No data wanted, only schema  
  7.         sqlCmd.CommandType = CommandType.Text;  
  8.         var sqlDR = sqlCmd.ExecuteReader();  
  9.         var dataTable = sqlDR.GetSchemaTable();  
  10.         foreach(DataRow row in dataTable.Rows) result.Add(row.Field < string > ("ColumnName"));  
  11.     }  
  12.     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

  1. WITH fs   
  2.      AS (SELECT database_id,   
  3.                 type,   
  4.                 size * 8.0 / 1024 size   
  5.          FROM   sys.master_files)   
  6. SELECT NAME,   
  7.        (SELECT Sum(size)   
  8.         FROM   fs   
  9.         WHERE  type = 0   
  10.                AND fs.database_id = db.database_id) DataFileSizeMB,   
  11.        (SELECT Sum(size)   
  12.         FROM   fs   
  13.         WHERE  type = 1   
  14.                AND fs.database_id = db.database_id) LogFileSizeMB   
  15. FROM   sys.databases db   

C# code

  1. public void GetDatabaseListwithsizeinMB(string conString) {  
  2.         using(SqlConnection con = new SqlConnection(conString)) {  
  3.                 con.Open();  
  4.                 using(SqlCommand cmd = new SqlCommand(@ "with fs  
  5.                         as(select database_id, type, size * 8.0 / 1024 size from sys.master_files) select name, (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB, (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB from sys.databases db ", con)) {  
  6.                         using(IDataReader dr = cmd.ExecuteReader()) {  
  7.                             while (dr.Read()) {  
  8.                                 Console.WriteLine(dr[0] + " " + dr[1] + " " + dr[2]);  
  9.                             }  
  10.                         }  
  11.                     }  
  12.                 }  

Get all the table names with row count

SQL Query

  1. DECLARE @QueryString NVARCHAR(max);   
  2.   
  3. SELECT @QueryString = COALESCE(@QueryString + ' UNION ALL ''')   
  4.                       + 'SELECT ' + ''''   
  5.                       + Quotename(Schema_name(sOBJ.schema_id))   
  6.                       + '.' + Quotename(sOBJ.NAME) + ''''   
  7.                       + ' AS [TableName] , COUNT(*) AS [RowCount] FROM '   
  8.                       + Quotename(Schema_name(sOBJ.schema_id))   
  9.                       + '.' + Quotename(sOBJ.NAME) + ' WITH (NOLOCK) '   
  10. FROM   sys.objects AS sOBJ   
  11. WHERE  sOBJ.type = 'U'   
  12.        AND sOBJ.is_ms_shipped = 0x0   
  13. ORDER  BY Schema_name(sOBJ.schema_id),   
  14.           sOBJ.NAME;   
  15.   
  16. EXEC Sp_executesql   
  17.   @QueryString   

C# Code

  1. public void GetallthetablenameswithrowcountNumber string conString) {  
  2.     using(SqlConnection con = new SqlConnection(conString)) {  
  3.         con.Open();  
  4.         using(SqlCommand cmd = new SqlCommand(@ "DECLARE @QueryString NVARCHAR(MAX) ;  
  5.                 SELECT @ QueryString = COALESCE(@QueryString + ' UNION ALL ''') + 'SELECT ' + ''  
  6.                 '' + QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) + ''  
  7.                 '' + ' AS [TableName], COUNT( * ) AS[RowCount] FROM ' + QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) + ' WITH (NOLOCK) '  
  8.                 FROM sys.objects AS sOBJ WHERE sOBJ.type = 'U'  
  9.                 AND sOBJ.is_ms_shipped = 0x0 ORDER BY SCHEMA_NAME(sOBJ.schema_id), sOBJ.name; EXEC sp_executesql @ QueryString ", con)) {  
  10.                 using(IDataReader dr = cmd.ExecuteReader()) {  
  11.                     while (dr.Read()) {  
  12.                         Console.WriteLine(dr[0] + " " + dr[1]);  
  13.                     }  
  14.                 }  
  15.             }  
  16.         }  
  17.     }  

Apart from all the above, if you want to have all the tables and table headers in a CSV file, I wrote the code for this.

Output Format

Tablename

   
 

Columnheader1

Columnheader2

Columnheader3

Here is my GitHub repo where you can find the project: MetaDataofyourDatabase