Solved

Copy a SQL Server Table using VBA

Posted on 2009-07-06
16
578 Views
Last Modified: 2013-11-27
How do I copy a SQL Server Table using VBA?

Below is the code that I used when the table was in an Access back-end
Public Sub CheckCopyTable()

  On Error Resume Next

  Dim acc As Access.Application

  Dim tbl As DAO.TableDef

  Dim strBackend_Path As String

  Dim db As Database

  Dim tdf As TableDef

  

  strBackend_Path = DB_Param("DB_ServerPath") & DB_Param("DB_BackendName")

  Set acc = New Access.Application

  acc.OpenCurrentDatabase (strBackend_Path)

  Set tbl = acc.CurrentDb.TableDefs("Commitment_Outlook_bak")

  If Err.Number <> 0 Then

    If Err.Number = 3265 Then

      Set db = OpenDatabase(strBackend_Path)

      db.TableDefs("Commitment_Outlook_new").Name = "Commitment_Outlook_bak"  'new to bak

    Else

      LogEvt "Error Number " & Err.Number & vbNewLine & Err.Description, vbExclamation, "CheckCopyTable Error (SB-123)", NOMSG

    End If

  End If

  acc.CloseCurrentDatabase

  Set acc = Nothing

End Sub

Open in new window

0
Comment
Question by:schmir1
  • 8
  • 5
  • 2
  • +1
16 Comments
 

Author Comment

by:schmir1
ID: 24798576
Anyone have an idea on how to copy tables on a SQL Server?
0
 
LVL 38

Accepted Solution

by:
Jim P. earned 400 total points
ID: 24799569
You would have to do it via the ADO objects.

It would something on the order of a "SELECT * INTO MyNewTable FROM MyOldTable". Or you would have to do it as a

CREATE TABLE MyTable (
MyIndexNum Integer Identity(1,1),
MyText Varchar(40),
MyNum Integer
blah....)
0
 

Author Comment

by:schmir1
ID: 24805018
So I would have to "CREATE TABLE MyNewTable" then do the "SELECT * INTO MyNewTable FROM MyOldTable".
0
 
LVL 38

Expert Comment

by:Jim P.
ID: 24805149
You can do a straight Select * Into, but you lose the primary keys, identity fields, etc.

It depends on what you are trying to do.
0
 

Author Comment

by:schmir1
ID: 24882649
I'm still not sure I'm following.  I would like to maintain the primary keys, idendtity fields, etc.  Can you give me an example of how to copy the table and all the data in it to another table and have them both have identical data structures?
0
 
LVL 49

Expert Comment

by:Gustav Brock
ID: 24882997
You would need a tool for that. Access has an "upgrade" wizard for moving tables from Access to SQL Server but not the other way.

Try DeZign:

http://www.datanamic.com/dezign/index.html

<quote>
Supported Databases
Oracle, MS SQL Server, MySQL, IBM DB2, Firebird, InterBase, MS Access, PostgreSQL, Paradox, dBase, Pervasive, Informix, Clipper, Foxpro, Sybase, SQLite, ElevateDB, NexusDB, DBISAM More.
</quote>

/gustav
0
 

Author Comment

by:schmir1
ID: 24883052
This is something that I need to run in my code.
0
 
LVL 34

Expert Comment

by:jefftwilley
ID: 24886321
is it linked into your Access Database?

You could give the CopyObject method a go

DoCmd.CopyObject, "Employees Copy", acTable, "Employees"


J
0
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
LVL 38

Expert Comment

by:Jim P.
ID: 24887369
>> You could give the CopyObject method a go

The issue is he wants a copy of the original table -- including structure in the BE. The CopyObject just refers to a newly named front end link.
0
 

Author Comment

by:schmir1
ID: 24910815
Jimpen is exactly right.  I need something that runs on the SQL Server but I kick off with my VBA.  Here is basically what the code needs to do:

1) I already have code that "INSERTS" the new data into "Commitment_Outlook_bak"

2) If successful then I need code to copy  Table "Commitment_Outlook" to Table "Commitment_Outlook_sav"

3) If this is successful then copy Table "Commitment_Outlook_bak" to "Comitment_Outlook"

Would it be hard to make a stored procedure and run it from my code.   Could I do a stored procedure that copies directly into "Commitment_Outlook" and roll back if there is a failure?
0
 

Author Comment

by:schmir1
ID: 24910832
I don't think my Stored Procedure idea is going to work.  I just remembered that the table that I'm getting the data from is a Outlook Address list that is resident on my C drive.
0
 
LVL 49

Assisted Solution

by:Gustav Brock
Gustav Brock earned 100 total points
ID: 24912139
If so, you can just use

DoCmd.TransferDatabase ...

Look up the on-line help for the full syntax and options.

Use acImport and acTable and study the example for how to include your connection string (which you can look up by linking the table and view the properties of the link table).

/gustav
0
 

Author Comment

by:schmir1
ID: 24956782
I don't think the DoCmd.TransferDatabase is going to work?  

I think I've found a way.  See code below.

If there is no other input then I'll close this question.
Function CreateSPT(SPTQueryName As String, strSQL As String)

'Generate a Pass-Through query then run it

'Params: SPTQueryName - name of the query (will be deleted and recreated if exists),

'        strSQL - query to run on SQL Server include Stored Procedures (Using EXEC)

'Example 1: CreateSPT ("Test", "Select * from Users")  'creates a Pass-Through Query called test with the "Select..." statement

'Example 2: CreateSPT("Generic_SPT", "EXEC RenameTBL ""Commitment_Outlook_bak"",""Commitment_Outlook_bak1""")

'Example 2: CreateSPT ("Generic_SPT", "EXEC sp_rename ""Commitment_Outlook_bak1"",""Commitment_Outlook_bak""")  'using system SP
 

  Dim cat As ADOX.Catalog

  Dim cmd As ADODB.Command
 

  DoCmd.Close acQuery, SPTQueryName

  On Error Resume Next

  DoCmd.DeleteObject acQuery, SPTQueryName

  On Error GoTo 0

  Set cat = New ADOX.Catalog

  Set cmd = New ADODB.Command

  cat.ActiveConnection = CurrentProject.Connection

  Set cmd.ActiveConnection = cat.ActiveConnection

  cmd.CommandText = strSQL

  cmd.Properties("Jet OLEDB:ODBC Pass-Through Statement") = True

'  cmd.Properties("Return Records") = bolReturnRecords  'no worky but On Error Resume Next stopped the error

  cmd.Properties("Jet OLEDB:Pass Through Query Connect String") = _

       "ODBC;DSN=DTLData_Dev;database=DTLData;UID=sa;PWD=;"

  cat.Procedures.Append SPTQueryName, cmd

  DoCmd.OpenQuery SPTQueryName
 

  Set cat = Nothing

  Set cmd = Nothing

End Function

Open in new window

0
 
LVL 38

Expert Comment

by:Jim P.
ID: 24961104
That looks to be the best solution.

Sorry we couldn't give you a better answer.
0
 

Author Closing Comment

by:schmir1
ID: 31600408
All good info although I found what I think is a good solution.  Thanks for your help.
0
 
LVL 38

Expert Comment

by:Jim P.
ID: 24962068
Glad to be of assistance. May all your days get brighter and brighter.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

The first two articles in this short series — Using a Criteria Form to Filter Records (http://www.experts-exchange.com/A_6069.html) and Building a Custom Filter (http://www.experts-exchange.com/A_6070.html) — discuss in some detail how a form can be…
Regardless of which version on MS Access you are using, one of the harder data-entry forms to create is one where most data from previous entries needs to be appended to new records, especially when there are numerous fields and records involved.  W…
In Microsoft Access, learn the trick to repeating sub-report headings at the top of each page. The problem with sub-reports and headings: Add a dummy group to the sub report using the expression =1: Set the “Repeat Section” property of the dummy…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

937 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now