Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add field to table programatically at runtime

Status
Not open for further replies.

briancoats

Programmer
May 1, 2003
61
US
I would like to check to see if a field already exists in a table and the add it to the table programatically if it does not. I am connecting to an access database through the data objecy (I know, don't kill me) but I can change that if I have to. I would appreciate any help with this as I can't seem to get it myself. Thanks.

Brian
 
Here is some code that will help you out. You will need to change it to match whatever database type your using. You will need a reference to Microsoft ActiveX Data Object 2.x and Microsoft ADO Ext. 2.7 for DDL and Security for this to work. This example is with an Access Database.

Code:
    Dim con As ADODB.Connection
    Dim cat As ADOX.Catalog
    Dim tbl As ADOX.Table
    Dim col As ADOX.Column
    Dim blnFound As Boolean
    
    Set con = New ADODB.Connection
    con.Provider = "Microsoft.Jet.OLEDB.4.0"
    
    con.Open "C:\db.mdb"
    
    Set cat = New ADOX.Catalog
    
    cat.ActiveConnection = con
    
    Set tbl = cat.Tables("Table1")
    
    blnFound = False
    For Each col In tbl.Columns
        If col.Name = "Column2" Then
            blnFound = True
            Exit For
        End If
    Next
    
    If Not blnFound Then
        tbl.Columns.Append "Column2", adVarWChar, 50
    End If
    Set tbl = Nothing
    Set cat = Nothing
    con.Close
    Set con = Nothing
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top