ADO.Net:从SQL服务器表中获取表定义

jav*_*ito 6 c# sql-server ado.net

我正在使用C#编写一个方法,该方法返回有关表的以下信息:列名,列类型,列大小,外键.

有人能指出我如何实现这个目标吗?

Chr*_*son 9

这实际上取决于您与数据库的通信方式.如果您正在使用LinqToSQL或其他类似的ORM,这将非常简单,但如果您想通过查询获取这些值,我建议您使用INFORMATION_SCHEMA视图,因为这些视图快速且容易查询.

例如

select * from information_schema.columns where table_name = 'mytable'
Run Code Online (Sandbox Code Playgroud)


cgr*_*eno 5

要获得FK和模式,您应该可以使用:

DA.FillSchema() 

DS.Table("Name").PrimaryKey 
Run Code Online (Sandbox Code Playgroud)

或使用下面演示的方法调用sp_fkey

代码段其他链接

    private void LoanSchema()
    {

         private List<String> tablesList = new List<String>();
         private Dictionary<String, String> columnsDictionary = new Dictionary<String, String>();

          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());
             }
}
Run Code Online (Sandbox Code Playgroud)