Create Table in Sql Database using Access VBA (1 Viewer)

Soniaski

Registered User.
Local time
Today, 13:41
Joined
Jun 20, 2012
Messages
21
I've spent the better part of today researching how to create a table in a SQL database via Access VBA. I can run a create table pass through query using the query tools, but when I convert it to code I get a "Data Type Conversion Error". Any and all help is appreciated.
 

Ranman256

Well-known member
Local time
Today, 16:41
Joined
Apr 9, 2015
Messages
4,337
Usually , you must use SQL manager app, create the table, THEN link it into Access.
(not the other way having Access make the table)
 

isladogs

MVP / VIP
Local time
Today, 21:41
Joined
Jan 14, 2017
Messages
18,219
I distribute several databases to clients with Access FE and SQL datafiles.
When there is a Access FE version update, it often includes changes to the SQL tables - new tables, extra fields etc

My approach to doing this is to distribute a script file as it is much more versatile

Attached is an example (zipped)
It has a .sql suffix for use by SQL Server but can be opened & edited in any text editor such as Notepad.

You'll see it includes code to check whether the changes have already been done.

It is easy to create these scripts in SQL Server Management Studio (SSMS) as it does most of the work for you

If you really want to do this from Access then this link may help you

https://stackoverflow.com/questions/21716199/using-access-to-do-a-make-table-query-to-create-a-sql-server-table-using-odbc-co

HTH
 

Attachments

  • SQL_AlterTables_SDA5295.zip
    1.3 KB · Views: 228

Soniaski

Registered User.
Local time
Today, 13:41
Joined
Jun 20, 2012
Messages
21
Thank you for the response Ridders. I'm still running into issues, but am slogging through the muck to figure it out. Wish me luck :)
 

isladogs

MVP / VIP
Local time
Today, 21:41
Joined
Jan 14, 2017
Messages
18,219
Thank you for the response Ridders. I'm still running into issues, but am slogging through the muck to figure it out. Wish me luck :)

Good luck! :rolleyes:

Forgot to say that you can of course run the SQL script from Access.
Would that be a good solution?

To do so:
1. Import the code below to a standard module
fHandleFile opens ANY file with the default application

Code:
Option Compare Database
Option Explicit

'Code Courtesy of Dev Ashish

###############################################
'Add PtrSafe - required for 64-bit Office (VBA7)
#If VBA7 Then
        Private Declare PtrSafe Function apiShellExecute Lib "shell32.dll" _
        Alias "ShellExecuteA" _
        (ByVal hWnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
        ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) _
        As Long
#ElseIf Win64 Then 'need datatype LongPtr
    Private Declare PtrSafe Function apiShellExecute Lib "shell32.dll" _
        Alias "ShellExecuteA" _
        (ByVal hWnd As LongPtr, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
        ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As LongPtr) _
        As LongPtr
#Else '32-bit Office
    Private Declare Function apiShellExecute Lib "shell32.dll" _
        Alias "ShellExecuteA" _
        (ByVal hWnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
        ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) _
        As Long
#End If


Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 2            'Open Maximized
Public Const WIN_MIN = 3            'Open Minimized

Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&


Function fHandleFile(stFile As String, lShowHow As Long)

Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)
            
    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function

'Now all you need to do is call the application with the path of the file and let Windows do the rest.
'This code can be used to start any registered applications, including another instance of Access.
'If it doesn't know what application to open the file with, it just pops up the standard "Open With.." dialog.
'It can even handle URL's and mailto:

'Open a folder:
'  fHandleFile("C:\TEMP\",WIN_NORMAL)

'Call Email app:
'  fHandleFile("mailto:bpo@yahoo.com",WIN_NORMAL)

'Open URL:
' fHandleFile("http://uk.yahoo.com";, WIN_NORMAL)

'Handle Unknown extensions:
' fHandleFile("C:\TEMP\TestThis",Win_Normal)

2. Create a sub similar to this
Replace the file path with the appropriate path

Code:
Sub RunSQLScript()

'replace line below with the correct path for your file
    strFile = "c:\somepath\SQL_AlterTables_SDA5295.sql"
    fHandleFile strFile, WIN_NORMAL
End Sub

You can try this on my example script
It will open SQL server with the script ready to run.... but obviously don't actually run it!
 

Soniaski

Registered User.
Local time
Today, 13:41
Joined
Jun 20, 2012
Messages
21
Almost there Ridders! I created a script and am using the fHandleFile to open the script in SQL. The problem is that SQL opens the script, but doesn't run it. Is there some setting that I need to change.

Please keep in mind that I am experienced in Access, but very much a novice when it comes to SQL Server. We've been using Access as our backend tables, but the size limitation of Access is starting to become a real concern.

Thank you for your help.
 

isladogs

MVP / VIP
Local time
Today, 21:41
Joined
Jan 14, 2017
Messages
18,219
It's the same for me.
If you find a way of running it automatically, do let me know!
 

isladogs

MVP / VIP
Local time
Today, 21:41
Joined
Jan 14, 2017
Messages
18,219
Hi Static

As the link explains, you can use a passthrough query to append/update/delete records from a SQL server table.

However, I don't believe you can use that method to do any of the following which the OP wants:
- create a new SQL table
- modify the fields in a SQL table
- delete a SQL table

That's why I suggested using a script which allows you to do all of these with ease

Do correct me if I'm wrong about passthrough or data definition queries and please provide an example if so.
Ditto re ADO
 

static

Registered User.
Local time
Today, 21:41
Joined
Nov 2, 2015
Messages
823
A passthrough query sends SQL directly to the server. Access doesn't process anything.
Any valid SQL should work.

It's no different than using ADO. You create the connection, send the SQL to the server.
 

jaryszek

Registered User.
Local time
Today, 13:41
Joined
Aug 25, 2016
Messages
756
Hi static,

A passthrough query sends SQL directly to the server. Access doesn't process anything.
Any valid SQL should work.

this is unfortunately not true. You can write sql scripts like ridders showed but you can not do it directly from Access...

Best,
Jacek
 

jleach

Registered User.
Local time
Today, 16:41
Joined
Jan 4, 2012
Messages
308
I'm not sure why you wouldn't... as stated, Access forwards the complete, unaltered statement directly to SQL Server, which will execute whatever you throw at it (provided the connection has the correct permissions of course).

Also, to run a script file "automatically" (without even having to load it via Access first), look at the SQLCMD.EXE utility (which should be installed alongside any given SQL Server instance). This is a very powerful command (running sql script files is one of many things it will do) that can be shelled easily from Access/VBA.

ex: https://docs.microsoft.com/en-us/sq...ransact-sql-script-files?view=sql-server-2017 (running a script file)

https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility?view=sql-server-2017 (full reference)

hth
 

jleach

Registered User.
Local time
Today, 16:41
Joined
Jan 4, 2012
Messages
308
this is unfortunately not true. You can write sql scripts like ridders showed but you can not do it directly from Access...

Is there a specific scenario you can replicate and explain here so we can see? I'm with static on this one.
 

jaryszek

Registered User.
Local time
Today, 13:41
Joined
Aug 25, 2016
Messages
756
Hi,

I am using postgrsql.
But i mean that i want to create form and have textbox to input sql statements there and after clicking button execute them in database BE.
I have to use command adodb property in order to do that.

The method here is awesome.
But i was trying to code and this is not working.
Errors with declaring functions statements and even public const declared variables are not working...

Best,
Jacek
 

jleach

Registered User.
Local time
Today, 16:41
Joined
Jan 4, 2012
Messages
308
I am using postgrsql.

Using a passthrough, this shouldn't matter (it still gets passed direct to the target server)

I have to use command adodb property in order to do that.

I'm not sure that's correct... why do you feel you must use ADODB (as opposed to a DAO passthrough?)

But i was trying to code and this is not working.

What, specifically? Exact error messages and code being executed would be ideal for us to help troubleshoot.

Errors with declaring functions statements and even public const declared variables are not working...

This sounds much more like VBA errors rather than anything to do with the SQL you're trying to execute.
 

jaryszek

Registered User.
Local time
Today, 13:41
Joined
Aug 25, 2016
Messages
756
Hi,

thank you for answer.

Using a passthrough, this shouldn't matter (it still gets passed direct to the target server)

this will work but not for create or drop statements.

I'm not sure that's correct... why do you feel you must use ADODB (as opposed to a DAO passthrough?)

I like this article as answer:



"Again, this is the wrong question, rather, why is SQL Server faster than Access should be the question. If you ask Access to update 100,000 records using a native Access update query vs using ADODB, be prepared to have one or two cups of coffee while you wait. In general, if your process will run faster on the server, (and they almost always do), then use ADODB, otherwise use DAO."

Ok, problem with code solved. I do not know why i had erros before.

Best,
Jacek
 

jleach

Registered User.
Local time
Today, 16:41
Joined
Jan 4, 2012
Messages
308
>> this will work but not for create or drop statements. <<

Again, I'm curious to a specific scenario where this doesn't work. Can you supply one? I believe this to be incorrect, and that you should in fact be able to execute any DDL/DML from a passthrough (provided the connection has the required permissions).

>> this article <<

The statement you quoted is ill-informed an incorrect. The performance implications are much more complex than this. While it can be true, it certainly is not always true, and whether you use ADO or DAO has little (no) difference on the defining factors. https://dymeng.com/azure-series-05-database-performance/ (this is a 44 page essay I wrote on the topic, if you really want to know what drives it).

With that said, sounds like you're reasonably well squared away for your purposes, I just hate to let misinformation go about in the wild without being refuted :)

Cheers,
 

jaryszek

Registered User.
Local time
Today, 13:41
Joined
Aug 25, 2016
Messages
756
jleach,

thanks!

Scenario is here:

http://www.accessforums.net/showthread.php?t=72850

Thank you for article.
I do not have time to read this now but i will in the future.

I think debate between developers about DAO vs ADO is running all the time but with pleasure i want to find out about your point of view.

Best,
Jacek
 

jleach

Registered User.
Local time
Today, 16:41
Joined
Jan 4, 2012
Messages
308
>> I think debate between developers about DAO vs ADO is running all the time but with pleasure i want to find out about your point of view. <<

They're just two different ways to do essentially the same thing. ADO does some things that DAO can't (quite a bit, actually), but DAO is more integrated with the JET/ACE engine (e.g., Access) than ADO, and carries some advantages there as well. There is no right or wrong per se, but rather one or the other should be chosen based on varying factors (and, there's no reason that both can't be used as well, when needed).

The performance thing is a whole different boat to sail in and has lots to do with how you construct your queries (especially when you include both the local Access tables as well as remote server tables in the same query), but the driver and/data access library (DAO/ADO) is relatively insignificant compared to the core issues at play.

Myself, I typically go the "use DAO unless there's specific reason to use ADO" route. My specific reasons for using ADO are typically:

- Pre-checking a login prior to connecting DAO to ensure that the DAO connection strings don't get cached for the session prior to my having validated the server and user.
- Working with any sort of streams (such as uploading binary data into a database server, which is relatively rare, but ADO is far (far!) better at this)
- Certain DDL (against JET/ACE) that is easier with ADO
- Parameterized statements (rare, I'd prefer a DAO passthrough typically) or other less-usual requirements such as returning multiple datasets from a single query, etc.

With all that said, DAO does make up well more than 99% of my data access code in Access projects.

Cheers,
 

jaryszek

Registered User.
Local time
Today, 13:41
Joined
Aug 25, 2016
Messages
756
Wow,

thank you jleach!
It is good to know !

Did you check scenario in my link above? I think this is not possible to pass DDL using pass trough query...

Thank you,
Jacek
 

Users who are viewing this thread

Top Bottom