繁体   English   中英

通过SQL或OLEDB查找哪些Access表的列是自动增量的?

[英]Finding out through SQL or OLEDB which of an Access tables' columns is autoincremented?

我需要找到所有多个或非自动增量的主键,使它们成为普通键,并使主键成为自动增量列。 但我需要检查是否已经有一个自动增量列,所以我将它作为主键,以防它不是。

基于这篇关于如何通过使用DataReader GetSchemaTable方法和Visual C#.NET检索列模式的 Microsoft文章,我编写了一些代码供您选择自动增量设置为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

OleDbReader有一个GetSchemaTable方法。 您可以通过对每个表的基本选择来调用它,然后遍历返回的列并检查IsAutoIncrement。 https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getschematable(v=vs.110).aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM