Csharp/C#教程:如何在C#中确定SQL Server数据库列是否为自动增量?分享


如何在C#中确定SQL Server数据库列是否为自动增量?

我需要能够从DbConnection.GetSchema()返回的DataTable中确定SQL Server表中的特定列是否是标识/自动增量。 我无法直接查询系统表。

奇怪的是,如果我通过ODBC连接到SQL Server,返回的此类列的数据类型将返回为“int identity”(或“bigint identity”等),但如果我使用本机SQL Server驱动程序,则似乎没有区分“int”列和“int identity”列。 还有其他方法可以推断出这些信息吗?

DataTable具有Columns属性, DataColumn具有指示自动增量的属性 :

 bool isAutoIncrement = dataTable.Columns[iCol].AutoIncrement 

请参阅此StackOverflow线程

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 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; } 

我遇到了同样的问题。 据我所知,“自动增量列的实现方式不同,具体取决于您使用的数据库类型。它不会通过GetOleDbSchema公开。”

我没有找到任何其他方式,然后提到“kelloti”。 所以目前我对这个解决方案很好,因为目前我需要知道列是否是AutoIncrement我已经在内存中有表,所以我不需要再次查询数据库。

(我会把我的评论作为评论,但我还不能发表评论,所以我希望我不要把它弄得太乱……)

上述就是C#学习教程:如何在C#中确定SQL Server数据库列是否为自动增量?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1030854.html

(0)
上一篇 2022年1月13日
下一篇 2022年1月13日

精彩推荐