Search through SQL or OLEDB, which of the columns in the Access table is auto-incremented?

I need to find all the plural or non-synchronous primary keys, make them normal keys and make the primary key an auto-increment column. But I need to check if there is an auto-increment column, so I do this with the primary key, if that is not the case.

+4
source share
2 answers

Based on this Microsoft article on How to Get a Column Schema Using the DataReader Method of GetSchemaTable and Visual C # .NET I wrote a little code to select a field with auto-increment set to True,

  OleDbConnection cn = new OleDbConnection();
  OleDbCommand cmd = new OleDbCommand();
  DataTable schemaTable;
  OleDbDataReader myReader;

  //Open a connection to the SQL Server Northwind database.
  cn.ConnectionString = "...";
  cn.Open();

  //Retrieve records from the Employees table into a DataReader.
  cmd.Connection = cn;
  cmd.CommandText = "SELECT * FROM Employees";
  myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo);

  //Retrieve column schema into a DataTable.
  schemaTable = myReader.GetSchemaTable();

  var myAutoIncrements = schemaTable.Rows.Cast<DataRow>().Where(
              myField => myField["IsAutoIncrement"].ToString() == "True");

  foreach (var myAutoInc in myAutoIncrements)
  {
      Console.WriteLine((myAutoInc[0]));
  }

  Console.ReadLine();

  //Always close the DataReader and connection.
  myReader.Close();
  cn.Close();

IsAutoIncrement, True.

+3

All Articles