?
Solved

Dynamically create an Access Table

Posted on 2005-02-28
6
Medium Priority
?
456 Views
Last Modified: 2012-06-27
I want to create an access table that matches the schema/structure of another access table.  How can I do that?
0
Comment
Question by:trishmid
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 19

Expert Comment

by:arif_eqbal
ID: 13426459
Prepare a Create table Statement
eg, "Create Table MyTable (Field1 Text, Field2....)"
Then use CommandObject's ExecuteNonQuery to run the statement.

0
 

Author Comment

by:trishmid
ID: 13428797
I know I need to do that.  But I can't figure out how to build the "Create Table" Statement dynamically.  
0
 

Author Comment

by:trishmid
ID: 13429029
Here is the code:  (HOW DO I DETERMINE WHAT TO PUT IN fieldType?)

Dim myCon As OleDbConnection = New OleDbConnection(archiveCS)
myCon.Open()

Dim cmd As OleDbCommand
cmd = New OleDbCommand("select * from " + archiveTableName, myCon)
Dim rd As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)
Dim dt As DataTable = rd.GetSchemaTable
rd.Close()
myCon.Close()

Dim s As String
Dim fieldType As String
Dim precision As String
s = "create table " + archiveTableName + " ("

For Each row As DataRow In dt.Rows
      s = s + row.Item("columnname") + " " + fieldType + "(" + precision + "),"
Next

'remove the last comma and add close paren
s = s.Substring(0, s.Length - 1)
s = s + ")"

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 19

Expert Comment

by:arif_eqbal
ID: 13436343
Hi trishmid
Try this


   Private Function PrepareCreateStatement(ByVal DT As DataTable) As String
        Dim Col As DataColumn
        Dim TmpStr As String = "Create Table " & DT.TableName & " ("
        For Each Col In DT.Columns
            TmpStr &= Col.ColumnName & " " & GetDataTypeName(Col.DataType.Name) & ","
        Next
        If TmpStr.EndsWith(",") Then TmpStr = TmpStr.Substring(0, TmpStr.Length - 1)
        Return TmpStr & ")"
    End Function

    Private Function GetDataTypeName(ByVal FWDataType As String) As String
        Select Case FWDataType.ToUpper
            Case "STRING"
                Return "String"
            Case "DECIMAL"
                Return "Number"
            Case "DATETIME"
                Return "DateTime"
            Case Else
                Return FWDataType
        End Select
    End Function

'It would be called like this

        Dim CreateStatement As String = PrepareCreateStatement(YourDateTable)
                Dim Cn As New OleDbConnection(YourConnectionString)
        Dim Cmd As New OleDbCommand(CreateStatement, Cn)
        Cn.Open()
        Try
            Cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Cn.Close()
        Cn.Dispose()

0
 
LVL 19

Expert Comment

by:arif_eqbal
ID: 13436393
Ok this was the one based on an existing DataTable with data in it
If you get the Schema theings would change a bit
I'd just post that too...
0
 
LVL 19

Accepted Solution

by:
arif_eqbal earned 2000 total points
ID: 13436489
OK here it is


    Private Sub CmdCreateTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdCreateTable.Click
        Dim myCon As OleDbConnection = New OleDbConnection(archiveCS)
         myCon.Open()

         Dim cmd As OleDbCommand
         cmd = New OleDbCommand("select * from " + archiveTableName, myCon)
        Dim rd As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)
         Dim dt As DataTable = rd.GetSchemaTable
         rd.Close()
        myCon.Close()


        Dim CreateStatement As String = PrepareStatement(DT)
        Dim YourConnectionString As String = "Provider=Microsoft.Jet.OLEDB....."
        Dim Cn As New OleDbConnection(YourConnectionString)
        cmd.CommandText = CreateStatement
        cmd.Connection = Cn
        Cn.Open()
        Try
            Cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        Cn.Close()
        Cn.Dispose()

    End Sub

    Private Function PrepareStatement(ByVal DT As DataTable) As String
        Dim R As DataRow
        Dim TmpStr As String = "Create Table " & DT.TableName & " (" 'may be you'd put your Table name instead of DT.tableName
        For Each R In DT.Rows
            TmpStr &= R(0) & " " & GetDataTypeName(R) & ","
        Next
        If TmpStr.EndsWith(",") Then TmpStr = TmpStr.Substring(0, TmpStr.Length - 1)
        Return TmpStr & ")"
    End Function

 
    Private Function GetDataTypeName(ByVal Row As DataRow) As String
        'You should go for a comprehensive mapping of dataTypes check DbType Enumeration in MSDN, This mapping would change foe the Underlying DataBase, I mean different for Access/SQLServer/Oracle etc. This is for ACCESS

        Select Case Row(5).ToString
            Case "System.Boolean"
                Return "YesNo"
            Case "System.Byte"
                Return "Text(1)"
            Case "System.Char"
                Return "Text(" & Row(2) & ")"
            Case "System.DateTime", "System.Date"
                Return "DateTime"
            Case "System.Decimal", "System.Double", "System.Int16", "System.Int32", "System.Int64"
                Return "Number"
            Case "System.Object"
                Return "Memo"
            Case "System.String"
                Return "Text(" & Row(2) & ")"
        End Select

    End Function
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question