Get schema and schema collections
Applies to: .NET Framework .NET .NET Standard
The SqlConnection classes in the Microsoft SqlClient Data Provider for SQL Server implements a GetSchema method which is used to retrieve schema information about the database that is currently connected, and the schema information returned from the GetSchema method comes in the form of a DataTable. The GetSchema method is an overloaded method that provides optional parameters for specifying the schema collection to return, and restricting the amount of information returned.
Specifying the schema collections
The first optional parameter of the GetSchema method is the collection name which is specified as a string. There are two types of schema collections: common schema collections that are common to all providers, and specific schema collections which are specific to each provider.
You can query the Microsoft SqlClient Data Provider for SQL Server to determine the list of supported schema collections by calling the GetSchema method with no arguments, or with the schema collection name "MetaDataCollections". This will return a DataTable with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use.
Retrieving schema collections example
The following examples demonstrate how to use the GetSchema method of the Microsoft SqlClient Data Provider for SQL Server SqlConnection class to retrieve schema information about all of the tables contained in the AdventureWorks sample database:
using System;
using System.Data;
using Microsoft.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source = localhost; Integrated Security = true; Initial Catalog = AdventureWorks";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
DataTable table = connection.GetSchema("Tables");
// Display the contents of the table.
DisplayData(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
private static void DisplayData(System.Data.DataTable table)
{
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}
}
}