Search code examples
c#sql-servert-sqlmetadatagetschema

Query vs. C# method to retrieve database metadata


I need to retrieve for each table in the database the following info:

  1. All columns names
  2. For each column its type
  3. Type max length

The possible way to do that is to run a query (even can execute it using await, i.e. async):

select object_NAME(c.object_id), c.name, t.name, c.max_length
from sys.columns c
INNER JOIN sys.types t
    ON t.system_type_id = c.system_type_id

On the other hand there is GetSchema method on connection which makes the same:

DataTable columns = connection.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictions);
foreach (DataRow row in columns.Rows)
{
    string columnName = row[3].ToString();
    string columnDataType = row[7].ToString();   
    string columnDataTypeLen = row[8].ToString();
}

Which of the methods is better to use? Looks that second one should be faster - am I right? What about performance?


Solution

  • Use either method and cache the result

    Meta data doesn't change under normal operation so performance is a non-issue