【问题标题】:How to retrieve the auto increment field name from a table?如何从表中检索自增字段名称?
【发布时间】:2023-04-01 16:06:01
【问题描述】:

我正在编写一个函数来获取任何给定表中的 AutoIncrement 字段的名称

public sub GetID(ByVal tblName As String) As String
    Dim rs as RecordSet
    Dim fld as field

    For each fld in rs.Fields
        if fld.type = 'autoIncrement?'
            Exit for
        End If
    Next fld
    GetID = fld.Name
End Sub

我尝试在网上查找,但找不到 AutoIncrement 的 dao 字段类型。我注意到有一种名为 DbGuid 的类型似乎与此有关,但我不知道它是什么。我还看到了其他具有此类功能的 sql DBMS,但我在 MS Access 中找不到这样的功能。

这是一个大型数据库,我不知道 AutoIncrement 字段的名称可能是什么。所以我不能做一个 instr(fieldname, "id") 或类似的东西来找到它。

【问题讨论】:

    标签: ms-access vba dao


    【解决方案1】:

    属性字段可以是几个值的组合,这些值可以成为一个总值,请参阅:MSDNMSDN Forum

    我无法让 dbUpdateableField 打印出任何字段的值,但显然它是 32。

    Attribute: dbAutoIncrField    Long: 16      Binary: 0000000000010000
    Attribute: dbDescending       Long: 1       Binary: 0000000000000001
    Attribute: dbFixedField       Long: 1       Binary: 0000000000000001
    Attribute: dbHyperlinkField   Long: 32768   Binary: 1000000000000000
    Attribute: dbSystemField      Long: 8192    Binary: 0010000000000000
    Attribute: dbUpdateableField  Long: 0       Binary: 
    Attribute: dbVariableField    Long: 2       Binary: 0000000000000010
    

    因此,由于该字段是一个总数,因此您的标准 autoNum 字段将 17 表示为 dbAutoIncrField=16dbFixedField=1,因此您可以检查 fld.Attributes 的值是否为 17。根据链接帖子的 AND 执行按位与如果在正确的位置有一个,则返回 true。

    fld.Attributes 对您的自动 ID 字段的结果是:Name: AutoID Attributes: 17 Binary: 0000000000010001 所以您在 dbAutoIncrField 的位置有一个 1,在 dbFixedField 的位置有一个 1

    Private Function AutoNumberField(tableName As String) As String
         Dim dbs As DAO.Database
         Dim tdf As DAO.TableDef
         Dim fld As DAO.Field
    
         Set dbs = CurrentDb
         Set tdf = dbs.TableDefs(tableName)
         For Each fld In tdf.fields
             If fld.Attributes And dbAutoIncrField Then
                 AutoNumberField = fld.name
                 Exit Function
             End If
         Next fld
    End Function
    

    【讨论】:

    • 你能解释一下吗? if fld.attributes 是干什么用的?
    • @rosa 还有一点解释。
    猜你喜欢
    • 2012-06-21
    • 2010-10-19
    • 2021-12-26
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    相关资源
    最近更新 更多