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

Dan*_*ann 4 c# sql-server

我需要能够从DbConnection.GetSchema()返回的DataTable中确定SQL Server表中的特定列是否为identity / auto-increment。我不能直接查询系统表。

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

kel*_*oti 5

DataTable具有Columns属性,并DataColumn具有指示自动递增的属性

bool isAutoIncrement = dataTable.Columns[iCol].AutoIncrement
Run Code Online (Sandbox Code Playgroud)


Sco*_*ard 5

请参阅此StackOverflow线程

GetSchema()函数将不会返回您想要的信息。也不会检查DataTable架构属性。您将不得不降到较低的级别,这将取决于DBMS及其可能的版本。

下面的成员检索具有标识列的所有表,然后查找与作为参数传递的特定表匹配。可以修改代码以返回所有表,或者可以对查询进行优化以仅查找感兴趣的表。

// see: /sf/ask/6142321/
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;
}
Run Code Online (Sandbox Code Playgroud)