我正在使用C#编写一个方法,该方法返回有关表的以下信息:列名,列类型,列大小,外键.
有人能指出我如何实现这个目标吗?
这实际上取决于您与数据库的通信方式.如果您正在使用LinqToSQL或其他类似的ORM,这将非常简单,但如果您想通过查询获取这些值,我建议您使用INFORMATION_SCHEMA视图,因为这些视图快速且容易查询.
例如
select * from information_schema.columns where table_name = 'mytable'
要获得FK和模式,您应该可以使用:
DA.FillSchema() DS.Table("Name").PrimaryKey
或使用下面演示的方法调用sp_fkey
代码段从与其他链接
private void LoanSchema() { private ListtablesList = new List (); private Dictionary columnsDictionary = new Dictionary (); string connectionString = "Integrated Security=SSPI;" + "Persist Security Info = False;Initial Catalog=Northwind;" + "Data Source = localhost"; SqlConnection connection = new SqlConnection(); connection.ConnectionString = connectionString; connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "exec sp_tables"; command.CommandType = CommandType.Text; SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) tablesList.Add(reader["TABLE_NAME"].ToString()); } reader.Close(); command.CommandText = "exec sp_columns @table_name = '" + tablesList[0] + "'"; command.CommandType = CommandType.Text; reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) columnsDictionary.Add(reader["COLUMN_NAME"].ToString(), reader["TYPE_NAME"].ToString()); } }