Import data from Excel into SQL Server using queries - sql-server

If I am not allowed to use the import function of SQL Server to bring data from Excel into SQL Server, would you be able to use queries to import the data?

There are several ways to export data from Excel to SQL Server. Here is one concept.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=server_name"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=server_name;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub

Related

How to update SQL Server table from Excel data

I've a vendor table in SQL Server with vendor code, vendor ID and vendor name. Another table called disc_mast with columns vendor ID and disc_per. Vendors will revise disc% frequently and we will get the details in Excel with vendor code and disc%. How can I update the discount percent in the disc_mast from the data in excel without importing the data in Excel to SQL Server tables.
You can do something like this.
Sub Update()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Your_Server_Name;Database=Northwind;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
This is VBA code that runs in Excel. Also, create a reference to 'Microsoft ActiveX Data Objects x.x Library'.
Tools -. References:

ADODB Connection to SQL-Server via Excel

I opened a similar question before with no avail on:
'https://stackoverflow.com/questions/58408918/vba-runtime-error-when-connection-to-sql-database
but since a few things have been tried, I thought I'd try again.
The problem is with the "Open" command". I get a runtime error 80040e4d Error on login for the user 'XXXX'
I looked at a stack link with similar issue which unfortunately didn't help either:
VBA Runtime Error when connection to SQL Database
I also tried usind the connection wizard in Excel which worked, so my connection data is seemingly correct. I wanted to use the connection string used by excel for my code in my modul,but the main difference of the provider being "Microsoft.Mashup.OleDb.1" didn't really change anything.
Here is my code:
'''
Sub DBCOnnectII()
Dim cnConn As ADODB.Connection
Set cnConn = New ADODB.Connection
With cnConn
.Provider = "SQLOLEDB.1"
.CursorLocation = adUseClient
.ConnectionTimeout = 0
.Properties("Data Source").Value = "VMSQL19"
.Properties("Password").Value = "XXXX"
.Properties("User ID").Value = "XXXX"
.Properties("Initial Catalog").Value = "AuswertungenTest"
.Open
End With
End Sub
'''
Here try this more simplified approach. Make sure to add the correct reference to use the ADO libraries.
Private Sub NonRecordset()
Dim vbSql As String, cnnstr as String
Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
vbSql = vbSql & "SQL STATEMENT"
Debug.Print ; vbSql
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB;Data Source=YOURSERVER;Initial Catalog=YOURDATABASE;User ID=USERNAME;Password=PASSWORD; Trusted_Connection=No"
cnn.Open cnnstr
' cnn.Execute vbSql 'use this if just executing statement
' rs.Open vbSql, cnn 'use this if needing recordset
' if needing a recordset you'lll have to do something with said recordset:
' ThisWorkbook.Sheets("Sheet1").Range("A1").CopyFromRecordset rs
cnn.Close
Set cnn = Nothing
End Sub
I found out how complicated it is via this website, which gives all possible entries:
https://www.connectionstrings.com/ole-db-driver-for-sql-server/
For my purposes with ADO, and a trusted connection( windows authenticated) it was this one:
con.Open "Provider=MSOLEDBSQL;Server=vmsql19;Database=XXXX;Trusted_Connection=yes;"
Here is an example of Inert Into.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=your_server_name"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
Here is an example of Select.
Sub ImportFromSQLServer()
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"
Database_Name = "your_db_name"
'User_ID = "******"
'Password = "****"
SQLStr = "select distinct ID from mytable1"
Set Cn = New ADODB.Connection
Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
RS.Open SQLStr, Cn, adOpenStatic
With Worksheets("Sheet1").Range("A1")
.ClearContents
.CopyFromRecordset RS
End With
RS.Close
Set RS = Nothing
Cn.Close
Set Cn = Nothing
End Sub

VBA to open and run .sql file and copy the result in excel

I am a bit new to this so my apologies in advance for any mistakes. I am trying to open and execute a sql query which is saved in C drive. The sql works fine. I did not write that sql and it is a very big file so would not like to add the code in VBA. I have been searching on this site and other places but struggling to make this work. I have had some or the other problem each time. I am pasting the code below for you to have a look and help me please. I have created this function which I am using in my VBA code.
Public Function ss()
'Open Connection
Dim oCon As ADODB.Connection
Set oCon = New ADODB.Connection
'Set Connection String
Dim sCon As String
sCon = "Provider=SQLOLEDB;Persist Security Info=True;User
ID='*****';Password='*****';Initial Catalog=****;Data Source=*******;Use
Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption
for Data=False;Tag with column collation when possible=False"
oCon.Open sCon 'Connect established
'Create recordset
Dim ps As ADODB.Recordset
Set ps = New ADODB.Recordset
'Set & execute SQL Command
Dim pCMD As ADODB.Command
Set pCMD = New ADODB.Command
Set pCMD.ActiveConnection = oCon
Dim filename As String
filename = "C:\Users\???????????\******.sql"
'select data
pCMD.CommandText =
CreateObject("scripting.filesystemobject").opentextfile(filename).ReadAll()
Set ps = pCMD.Execute(, , adCmdText)
Debug.Print ps.GetRows
If ps.EOF = False Then Sheets("Sheet2").Range("A1").CopyFromRecordset ps
'Close connection
Set ps = Nothing
Set pCMD = Nothing
oCon.Close
Set oCon = Nothing
End Function
Debug.Print has only been used to see the result but it is showing the same error "Run-time error '3704' Operations is not allowed when the object is closed. After trying so many different things I am not sure what is it that I am doing wrong.
Can someone please help?
Any help will be really appreciated.
For me the easiest solution for you is to modify the end of the stored procedure so when executed, it insert all the results in a table. The next time you execute the SP you just have to TRUCATE the table and INSERT new results.
Execute the SP
You can call the SP from Excel with VBA using some code you can find here on StackOverflow, for example the following (which I've taken from this answer):
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
Retrive results into Excel
Now that the results of the SP are stored into a table of you DB you can import them into Excel with ODBC connection as shown here or with this procedure.

vba mssql connection error

I am trying to connect sql with Access.
What I want to do is simply get data from mssql using select statement.
Here is the code.
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
strSQL = "SELECT * FROM dbo.Version"
cmd.Execute
conn.Close
Set conn = Nothing
Set cmd = Nothing
End Sub
When I execute this code, I get error like "[Microsoft][ODBC SQL Server Driver][SQL Server] The request for procedure 'Version' failed because 'Version' is a table object.'
I know that I need to add something after "strSQL = SELECT * FROM dbo.Version" but I do not know exactly how to fill in.
Could you please help me with this?
It looks like you are executing dbo.Version as a SP or a SQL Command which is wrong.
You should execute the command in strSQL object instead. So after the modifications your code will look something like this:
strSQL = "SELECT * FROM dbo.Version"
Set cmd = New ADODB.Command
cmd.CommandText = strSQL
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = conn
EDIT 1
I replicated the same issue in MS Excel to read data from MS SQl Server by using the following code and it worked for me:
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyRecordset = New ADODB.Recordset
Dim strSQL As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=HARSH-SHARMA\SQLEXPRESS;Initial Catalog=db1;User ID=sa;Password=pass001;"
objMyConn.Open
'Set and Excecute SQL Command'
strSQL = "select * from Subject"
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open strSQL
'Copy Data to Excel'
ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
Please try this.

Using SQL script through vb.net code

I am new to SQL Server. I often find scripts over internet to perform different functions with SQL Server but I donot know how to use them in vb.net.
For example I want to run the following code through my vb.net application, but donot know how to do so. Please advise
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '' ;
GO
Thanks
The following code might help. Its from http://www.daniweb.com/software-development/vbnet/code/216920
'Declare outside of class
Imports System.Data.SqlClient
'Declare inside of class >
Dim SQLStr As String
Private ConnString As String
'Connstring = Server Name, Database Name, Windows Authentication
connstring = "Data Source=myserver;Initial Catalog=databasename;Integrated Security=True"
'SQL Staments
'SQL query = myQuery = "SQL Statment"
SQLStr = "SELECT * FROM tblQuestion"
SQLStr = "INSERT into tblQuestion(Name, Question) VALUES('Fred', 'How to use SQL?')"
SQLStr = "UPDATE tblQuestion SET Answer = 'Like this' Where Question = 'How to use SQL?'"
SQLStr = "DELETE FROM tblQuestion WHERE Question='How to use SQL?'"
'Write to SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only
SQLConn.Close() 'Close the connection
'Read from SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
Dim SQLdr As SqlDataReader 'The Local Data Store
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLdr = SQLCmd.ExecuteReader 'Gets Data
While dr.Read() 'While Data is Present
MsgBox(dr("Column Name")) 'Show data in a Message Box
End While
Loop While SQLdr.NextResult() 'Move to the Next Record
SQLdr.Close 'Close the SQLDataReader
SQLConn.Close() 'Close the connection

Resources