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

时间:2011-01-29 01:46:39

标签: c# sql-server

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

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

3 个答案:

答案 0 :(得分:4)

DataTableColumns属性,DataColumna property表示自动增加:

bool isAutoIncrement = dataTable.Columns[iCol].AutoIncrement

答案 1 :(得分:4)

请参阅This StackOverflow thread

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

答案 2 :(得分:0)

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

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

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