加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:19:09 所属栏目:百科 来源:网络整理
导读:我正在使用C#编写一个方法,该方法返回有关表的以下信息: 列名,列类型,列大小,外键. 有人能指出我如何实现这个目标的正确方向吗? 解决方法 要获得FK和Schema,您应该能够使用: DA.FillSchema() DS.Table("Name").PrimaryKey 或者使用下面演示的方法调用sp_f
我正在使用C#编写一个方法,该方法返回有关表的以下信息:
列名,列类型,列大小,外键.

有人能指出我如何实现这个目标的正确方向吗?

解决方法

要获得FK和Schema,您应该能够使用:
DA.FillSchema() 

DS.Table("Name").PrimaryKey

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

代码段from和Another Link

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());
             }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读