C# 如何在C中确定SQL Server数据库列是否为自动增量?
我需要能够从DbConnection.GetSchema返回的DataTable中确定SQL Server表中的特定列是否为identity/auto increment。我无法直接查询系统表 奇怪的是,如果我通过ODBC连接到SQL Server,则此类列返回的数据类型将作为int-identity或bigint-identity等返回。但如果我使用本机SQL Server驱动程序,则int列和int-identity列之间似乎没有区别。是否有其他方法可以推断该信息?DataTable具有Columns属性,DataColumn具有指示自动递增的属性:C# 如何在C中确定SQL Server数据库列是否为自动增量?,c#,sql-server,C#,Sql Server,我需要能够从DbConnection.GetSchema返回的DataTable中确定SQL Server表中的特定列是否为identity/auto increment。我无法直接查询系统表 奇怪的是,如果我通过ODBC连接到SQL Server,则此类列返回的数据类型将作为int-identity或bigint-identity等返回。但如果我使用本机SQL Server驱动程序,则int列和int-identity列之间似乎没有区别。是否有其他方法可以推断该信息?DataTable具有Co
bool isAutoIncrement = dataTable.Columns[iCol].AutoIncrement
我也遇到过同样的情况。据我所知,根据您使用的数据库类型,自动增量列的实现方式有所不同。它不是通过GetOleDbSchema暴露的 除了@kelloti提到的以外,我没有找到其他方法。所以现在我对这个解决方案没意见,因为现在我需要知道列是否是.AutoIncrement。我的内存中已经有了这个表,所以我不需要再次查询数据库 @pesaak请将此答案转换为评论,因为您应该有足够的声誉。请参阅 GetSchema函数不会返回所需的信息。也不会检查DataTable架构属性。您必须转到较低的级别,这取决于DBMS及其版本 下面的成员检索所有具有标识列的表,然后查找是否匹配作为参数传递的特定表。可以修改代码以返回所有表,或者优化查询以仅查找感兴趣的表
// see: https://stackoverflow.com/questions/87747/how-do-you-determine-what-sql-tables-have-an-identity-column-programatically
private static string GetIdentityColumnName(SqlConnection sqlConnection, Tuple<string, string> table)
{
string columnName = string.Empty;
const string commandString =
"select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS "
+ "where TABLE_SCHEMA = 'dbo' and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 "
+ "order by TABLE_NAME";
DataSet dataSet = new DataSet();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = new SqlCommand(commandString, sqlConnection);
sqlDataAdapter.Fill(dataSet);
if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dataSet.Tables[0].Rows)
{
// compare name first
if (string.Compare(table.Item2, row[1] as string, true) == 0)
{
// if the schema as specified, we need to match it, too
if (string.IsNullOrWhiteSpace(table.Item1) || string.Compare(table.Item1, row[0] as string) == 0)
{
columnName = row[2] as string;
break;
}
}
}
}
return columnName;
}
他需要从GetSchema中获取它,GetSchema返回一个包含模式信息的数据表,而不是模式本身。对,我猜假设是对表进行一个小查询以获取包含此信息的数据表是一个坏主意。但如果真的要归结到这一点,也许这不是一个坏主意?它看起来不像GetSchema集合中提供的信息。为什么不能查询系统目录视图??这些肯定会保存这些信息!我需要一个独立于数据库的方式来做这件事。查询每个单独的表并检查DatabaseReader.GetSchemaTable的输出似乎是唯一可靠的方法。请将此移到comment。