vba insert existing table to a new table - sql-server

I am trying to insert table to new table.
This is my code and I am not sure how to proceed.
It is not a complete code.
Private Sub CommandSubmit_Click()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim strConn As String
Dim par As ADODB.Parameter 'input
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn 'open connection
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.SubmitBlend"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
Dim strBlend As String
strBlend = "INSERT INTO dbo.SubmitBlend SELECT * FROM dbo.AddBlendPrac"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
MsgBox "Request Submit Succeed"
I have create a table first, and this table has data. This table needs to be inserted to a new table. Is there any one how to code this one? Any comments would be greatly helpful :)

Related

Error: "Command text was not set for the command object" when running a Stored Procedure from SQL on VBA

I'm trying to run a stored procedure on VBA using the following VBA code:
Please can someone advise: I get the error at "rs.Open".
Sub connection()
Dim Conn As ADODB.connection
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim i As Integer
Dim constring As String
Dim location As String 'the server
Dim password As String
location = "10.103.98.18"
password = "password"
constring = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ElColibri; User ID=Analyst1; Password=password;"
Set Conn = New ADODB.connection
Conn.connectionString = constring
'On Error GoTo ConnectionError
Conn.Open
'loginstatus = False
'Exit Sub
'errorhandl0
'ConnectionError:
'MsgBox "Not possible to log in. Have you entered the correct password?"
'open recordset
Set ADODBCmd = New ADODB.Command
ADODBCmd.ActiveConnection = Conn
ADODBCmd.CommandTimeout = 1200
ADODBCmd.CommandText = ["ukrmc.dbo.FridayCommentary"]
ADODBCmd.CommandType = 4 'adCmdStoredProc
ADODBCmd.Execute
Set rs = New ADODB.Recordset
rs.ActiveConnection = Conn
rs.Open
Conn.Close
Set Conn = Nothing
Set ADODBCmd = Nothing
'Paste to spreadsheet
ThisWorkbook.Worksheets("macrotest").Range("a2").CopyFromRecordset
'Set rs = conn.Execute(Query)
rs.Close
Set rs = Nothing
End Sub
To me the code makes logical sense to me so I am not sure what the error means. Because to me, I have set text for the command object.
You are not connecting the recordset to your command. Assuming that your stored procedure issues a SELECT, change your code to
Set rs = ADODBCmd.Execute
thisWorkbook.Worksheets("macrotest").Range("a2").CopyFromRecordset rs
The Execute-Method will return a Recordset as result, no need to create one by yourself.
Or you should add the command object to the open operation
rs.Open ADODBCmd

VBA connecting to SQL Server

I am having trouble when connecting VBA to SQL Server:
Sub ConnectSQLServer()
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Dim par As ADODB.Parameter
Dim strSQL As String
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
Set conn = New ADODB.Connection
conn.Open strConn
Set cmd = New ADODB.Command
cmd.CommandText = "dbo.Version"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
rs.Open = "SELECT * FROM [dbo].[Version]"
cmd.Execute rs
Set conn = Nothing
Set cmd = Nothing
sConnString = ""
End Sub
I just want to select all values from the table named [dbo].[Version], but when I execute it, I get an error:
Compile error: Expected Function or Variable'
and the line with rs.Open is highlighted.
Would you help me to solve this problem?
Open is a method, and cannot be set with an =.
You probably want something like this:
rs.Open "SELECT * FROM [dbo].[Version]", conn
Once you have called Open, then you can iterate through the Recordset's rows using the EOF property and the MoveNext method:
Do While Not rs.EOF
Debug.Print rs.Fields(1)
'You could also use rs!FieldName, where FieldName is the name of a column
Loop
Change your code to the following:
Set cmd = New ADODB.Command
cmd.CommandText = "SELECT * FROM [dbo].[Version]"
cmd.CommandType = adCmdText
cmd.ActiveConnection = conn
Set rs = cmd.Execute
Do While Not rs.EOF
'do something with rs.Fields(0) '
rs.MoveNext
Loop
Set conn = Nothing
Set cmd = Nothing
rs.Fields is a zero based collection that means that the first field is 0, not 1.
You can get subsequent fields by rs.Fields(1), rs.Fields(2) etc. Or you can use Field names, with the syntax rs.Fields("MyFieldName").
Note when using a string command ("SELECT * FROM ..") the CommandType is adCmdText. The syntax for the Recordset is SET rs = cmd.Execute. Also you must invoke MoveNext in your loop, otherwise you get stuck in the loop!

VBA SQL Server Select

I was wondering if you could please check my code in VBA (Excel) to retrieve data from a SQL Server database, and insert it in the sheet.
It returns an error according the picture attached.
Sub ConnectionTest()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim constr As String
constr = "Provider=sqloledb;Data source=USO-YEGANEH\SQL2008;Initial Catalgo=USO_Final;User Id=sa;Password=123"
Dim conRS As ADODB.Recordset
Set conRS = New ADODB.Recordset
conn.Open constr
With conRS
.ActiveConnection = conn
.Open "Select * from LatLong_Amar"
Sheet1.Range("A1").CopyFromRecordset conRS
.Close
End With
End Sub
I found out what is the problem, it seems full path of the table, despite the fact that database is defined in the Connection String, should be entered. So, the line "Select * from LatLong_Amar" should be changed to [USO_Final].[dbo].[Latlong_Amar]
Sub ConnectionTest()
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim constr As String
constr = "Provider=sqloledb;Data source=USO-YEGANEH\SQL2008;Initial Catalgo=USO_Final;User Id=sa;Password=123"
Dim conRS As ADODB.Recordset
Set conRS = New ADODB.Recordset
conn.Open constr
With conRS
.ActiveConnection = conn
.Open "Select * from [USO_Final].[dbo].[Latlong_Amar]"
Sheet1.Range("A1").CopyFromRecordset conRS
.Close
End With
End Sub
You can do it this way.
Sub ADOExcelSQLServer()
Dim Cn As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Server_Name = "YOUR_SERVER_NAME" ' Enter your server name here
Database_Name = "AdventureWorksLT2012" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
' Dump to spreadsheet
With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here
.ClearContents
.CopyFromRecordset rs
End With
' Tidy up
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Here is another option for you to muse over.
Sub TestMacro()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=NORTHWIND.MDF;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
.Open "SELECT * FROM Categories"
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsPubs
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub

Cannot connect to sql server with VBA (Run-time error (80040e14))

I am trying to connect to my Sql database and get one simple recordset out of it running this code:
Sub ConnectToSQL()
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
With cnn
.ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
.Open
End With
With cmd
.ActiveConnection = cnn
.CommandType = xlCmdSql
.CommandText = "SELECT * FROM TEST"
End With
rs.Open cmd.Execute, cnn
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
rs.Close
Else
MsgBox "No records returned", vbCritical
End If
cn.Close
Set cn = Nothing
Set rs = Nothing
End Sub
As a result I get the run-time error message (80040e14) What could be wrong here?
Thanks,
Do you want to try following? Please do not forget to add Tools> Refernces if necessary.
Sub ConnectToSQL()
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim ConnectionString As String
Set cnn = New ADODB.Connection
ConnectionString = "File Name=C:\inetpub\tc\TEST.udl"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
strquery = "SELECT * FROM TEST;"
'MsgBox strquery
rs.Open strquery, cnn
If Not rs.EOF Then
Sheets(1).Range("A1").CopyFromRecordset rs
rs.Close
Else
MsgBox "No records returned", vbCritical
End If
cnn.Close
Set cnn = Nothing
Set rs = Nothing
End Sub

Execute SQL Server stored procedure through VBA which does not return rows

How to execute special SQL Server stored procedure through Excel VBA? Special because it does not return rows like this procedure:
select * from tab1
How to execute the procedure which let's say prepares reports, like this one:
select *
into tab2
from tab1
which does not return any rows.
I am using this VBA code:
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Sql = "EXEC [dbo].[Procedure_make_report] 'param1'"
Set rs = cnn.Execute(Sql)
I get the error:
Runtime error 2147217900
I found a clue here:
http://www.vbforums.com/showthread.php?541498-RESOLVED-runtime-error-2147217900-(80040e14)-incorrect-syntax-error
but I do not know what action query is.
Based on comments of Rory and Tom, I leave the answer which works.
Dim cnn As Object
Set cnn = CreateObject("ADODB.Connection")
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = 1 ' adCmdText
cmd.CommandTimeout = 120 ' number of seconds to time out
Dim ConnectionString As String
cnn.ConnectionString = "driver={SQL Server};server=MYSERVERNAME;Database=MYDATABASE;Trusted_Connection=yes;"
cnn.Open
Dim SQL As String
SQL = "EXEC [dbo].[Procedure_make_report] 'param1'"
cnn.Open
cmd.CommandText = SQL
cmd.ActiveConnection = cnn
cmd.Execute
If Not cnn Is Nothing Then
cnn.Close
Set cnn = Nothing
End If

Resources