ADO.Net : Get table definition from SQL server tables

后端 未结 5 475
梦毁少年i
梦毁少年i 2021-01-12 20:37

I am using C# to write a method that returns the following information about a table: column names, column types, column sizes, foreign keys.

Can someone point me in

5条回答
  •  借酒劲吻你
    2021-01-12 20:50

    To get the FK and Schema you should be able to use:

    DA.FillSchema() 
    
    DS.Table("Name").PrimaryKey 
    

    OR calling sp_fkey using the method demonstrated below

    Code Snippet from AND Another Link

        private void LoanSchema()
        {
    
             private List tablesList = 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());
                 }
    }
    

提交回复
热议问题