GetSchema取得数据库架构,无法取得列的Description属性的解决方法
2012-11-13 09:38 zhoujie 阅读(1727) 评论(0) 编辑 收藏 举报通常我们通过如下方法取得数据库架构:
表:
SqlConnection conn = new SqlConnection(connectionstring);
conn.Open();
DataTable dt = conn.GetSchema(SqlClientMetaDataCollectionNames.Tables, new string[] { null, null, null, "BASE TABLE" });
DataView dv = new DataView(dt, "", "TABLE_NAME", DataViewRowState.CurrentRows);
for (int i = 0; i < dv.Count; i++)
{
DataRow row = dv[i].Row;
string tbname = row["TABLE_NAME"].ToString();
//todo
}
conn.Open();
DataTable dt = conn.GetSchema(SqlClientMetaDataCollectionNames.Tables, new string[] { null, null, null, "BASE TABLE" });
DataView dv = new DataView(dt, "", "TABLE_NAME", DataViewRowState.CurrentRows);
for (int i = 0; i < dv.Count; i++)
{
DataRow row = dv[i].Row;
string tbname = row["TABLE_NAME"].ToString();
//todo
}
列:
DataTable dt = conn.GetSchema(SqlClientMetaDataCollectionNames.Columns, new string[] { null, null, TableName, null });
DataView dv = new DataView(dt, "", "COLUMN_NAME", DataViewRowState.CurrentRows);
for (int i = 0; i < dv.Count; i++)
{
DataRow row = dv[i].Row;
string colname = row["COLUMN_NAME"].ToString();
}
DataView dv = new DataView(dt, "", "COLUMN_NAME", DataViewRowState.CurrentRows);
for (int i = 0; i < dv.Count; i++)
{
DataRow row = dv[i].Row;
string colname = row["COLUMN_NAME"].ToString();
}
但是这种方法无法取得列描述信息,只能靠读取系统表的方法,不同数据库的sql语句是不同的,这里给出的是sql server 2008数据库:
select s.name,e.value from sys.extended_properties e
left join sys.all_columns s on e.major_id=s.object_id and e.minor_id=s.column_id
left join sys.tables t on e.major_id=t.object_id
left join sys.all_columns s on e.major_id=s.object_id and e.minor_id=s.column_id
left join sys.tables t on e.major_id=t.object_id
where e.name='MS_Description' and t.name='TableName'