假设我有一个带有列c1的表t1。当我从t1'执行'选择c1时,我可以使用DataTable / DataRow / DataColumn使用下面的代码片段获取结果的元数据
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
SqlDataAdapter adapter;
DataSet dataset = new DataSet();
using (SqlConnection connection
= new SqlConnection(@"Persist Security Info=False;Trusted_Connection=True;"))
{
SqlCommand command = new SqlCommand(
@"SELECT c1 from t1 where 1 = 0;", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable schemaTable = reader.GetSchemaTable();
Console.WriteLine(reader.GetName(0)); //Name of column
foreach (DataRow row in schemaTable.Rows)
{
//Console.WriteLine(row["TableName"]);
foreach (DataColumn column in schemaTable.Columns)
{
Console.WriteLine(String.Format("{0} = {1}",
column.ColumnName, row[column]));
}
}
}
}
}
}
但是为BaseTableName返回的值是空白的。有没有其他方法可以获得表格' t1'与列' c1'?
相关联以下是上述代码的输出:
ColumnName = c1
ColumnOrdinal = 0
ColumnSize = 100
NumericPrecision = 255
NumericScale = 255
IsUnique = False
IsKey =
BaseServerName =
BaseCatalogName =
BaseColumnName = c1
BaseSchemaName =
BaseTableName =
DataType = System.String
AllowDBNull = True
ProviderType = 3
IsAliased =
IsExpression =
IsIdentity = False
IsAutoIncrement = False
IsRowVersion = False
IsHidden =
IsLong = False
IsReadOnly = False
ProviderSpecificDataType = System.Data.SqlTypes.SqlString
DataTypeName = char
XmlSchemaCollectionDatabase =
XmlSchemaCollectionOwningSchema =
XmlSchemaCollectionName =
UdtAssemblyQualifiedName =
NonVersionedProviderType = 3
IsColumnSet = False
答案 0 :(得分:0)
您可以使用
获取表名schemaTable.TableName
以下链接将为您提供所需的信息:
https://msdn.microsoft.com/en-us/library/system.data.datatable.tablename(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.data.datarow.table(v=vs.110).aspx
答案 1 :(得分:0)
尝试以下操作以获取所有表/列信息
Select * From INFORMATION_SCHEMA.COLUMNS
答案 2 :(得分:0)
你几乎得到了它:
//Console.WriteLine(row["table_name"]);
尝试将其更改为:
Console.WriteLine(row["TableName"]);