我需要找到所有多个或非自动增量的主键,使它们成为普通键,并使主键成为自动增量列。但是我需要检查是否已经有一个自动增量列,所以我把它作为主键,以防它不是。
答案 0 :(得分:3)
根据这篇关于How To Retrieve Column Schema by Using the DataReader GetSchemaTable Method and Visual C# .NET的微软文章,我为您编写了一些代码,用于选择自动增量设置为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
。
答案 1 :(得分:2)
OleDbReader有一个GetSchemaTable方法。您可以通过对每个表的基本选择来调用它,然后遍历返回的列并检查IsAutoIncrement。 https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getschematable(v=vs.110).aspx