Synopsis
DataTable dt
= DataReader.GetSchemaTable();
Returns a DataTable
that contains metadata for the
current query. This table contains one row for each column in the
result set and several fields that describe details such as column
names and data types. Table 21-2 lists all columns
returned in the schema DataTable
, in order.
Table 21-2. Schema columns
Column
|
Description
|
ColumnName
|
The name of the column. If the query renamed the column using the AS
keyword, this is the new name.
|
ColumnOrdinal
|
The ordinal number of the column.
|
ColumnSize
|
The maximum allowed length of values in the column or the size of the
data type for fixed-length data type.
|
NumericPrecision
|
The maximum precision (number of digits) of the column for a numeric
data type or null for all other data types.
|
NumericScale
|
The maximum scale (number of digits to the right of the decimal
point) of the column for a numeric data type, or
null for all other data types.
|
IsUnique
|
Indicates whether or not column values can be duplicated.
|
IsKey
|
Indicates whether or not this column is part of the primary key for
the table.
|
BaseCatalogName
|
The name of the database that contains this table, or
null if it can’t be determined.
|
BaseColumnName
|
The name of the column in the data source. If the query renamed the
column using the AS keyword, this is the original name.
|
BaseSchemaName
|
The name of the schema in the data source, or null
if it can’t be determined.
|
BaseTableName
|
The name of the table or view in the data source that contains this
column, or null if it can’t be
determined.
|
DataType
|
The mapped .NET framework type.
|
AllowDBNull
|
Indicates whether null values are accepted for
column values.
|
ProviderType
|
Indicates the provider-specific data type.
|
IsAliased
|
True if the column has been renamed using the AS keyword.
|
IsExpression
|
True if the column is calculated based on an expression.
|
IsIdentity
|
True if the column is an identity value generated by the data source.
|
IsAutoIncrement
|
True if column values are assigned by the data source in fixed
increments.
|
IsRowVersion
|
True if the column contains a read-only row identifier.
|
IsHidden
|
True if the column is hidden.
|
IsLong
|
True if the column contains a binary long object (BLOB).
|
IsReadOnly
|
True if the column can’t be modified.
|
Example
The following example retrieves a schema table and displays the
returned information. The schema information describes the columns
from the Customers
table.
SqlCommand cmd = new SqlCommand("SELECT * FROM CUSTOMERS", con);
// Get the schema table.
con.Open();
SqlDataReader r = cmd.ExecuteReader();
DataTable schema = r.GetSchemaTable();
con.Close();
// Display schema table information.
foreach (DataRow row in schema.Rows)
{
foreach (DataColumn col in schema.Columns)
{
Console.WriteLine(col.ColumnName + " = " + row[col].ToString());
}
Console.WriteLine();
}