Sample Code Primary key in a table

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Austen
    New Member
    • Oct 2006
    • 23

    #1

    Sample Code Primary key in a table

    hello,
    im using microsoft access as my Db. i need a primary key in my table and i have to generate the table in vb code.

    how to write the statement to create a primary key in a table ?
    can someone proovide me a simple sample code for it ?
    thanks
  • MMcCarthy
    Recognized Expert MVP
    • Aug 2006
    • 14387

    #2
    To create a table:

    Code:
     
    Public Sub CreateTable() 
    Dim db As Database 
    Dim tbl As TableDef 
    Dim fld As Field 
    Dim idx As Index
     
    	' Start by opening the database 
    	Set db = CurrentDb() 
    
    	' Create a tabledef object 
    	Set tbl = db.CreateTableDef("TableName") 
    
    	' Create a field; set its properties; add it to the tabledef 
    	Set fld = tbl.CreateField("ID_Field", dbLong) 
    	fld.OrdinalPosition = 1 ' set as first field
    	fld.Attributes = dbAutoIncrField 'make autonumber
    	tbl.Fields.Append fld ' add the field
    
    	' Create another; set its properties; add it to the tabledef 
    	Set fld = tbl.CreateField("NextFieldName", dbText) 
    	fld.OrdinalPosition = 2 ' set as second field
    	fld.Size = 50 
    	fld.Required = True ' nulls not allowed
    	fld.AllowZeroLength = False 
    	tbl.Fields.Append fld 
    
    	' Make ID_Field the primary key
    	Set idx = tbl.CreateIndex("PrimaryKey") 
    	idx.Primary = True 
    	idx.Required = True 
    	idx.Unique = True 
    	' Add a field to the index 
    	Set fld = idx.CreateField("ID_Field") 
    	idx.Fields.Append fld 
     
    	' Add the index to the tabledef 
    	tbl.Indexes.Append idx 
    
    	' Finally add table to the database 
    	db.TableDefs.Append tbl 
    
    	' And refresh the database window 
    	RefreshDatabaseWindow 
    
     
    	set idx=Nothing
    	set fld=Nothing
    	set tbl=Nothing
    	set db=Nothing
     
    End Sub

    Comment

    Working...