I'm making an Excel report using 3 SQL Server queries one of which selects into a temp table and I want the result of these select statements into an Excel table. I am new to Excel what is a good way to display the query result as a table and be able to refresh the table with new data from these 3 queries? I've read about power query is this a good option?
my queries
Select into temp table
join temp table with table
join temp table with table
union above 2 into 1 result table
Ended up using Data->Get Data->From Database to load the SQL data into excel and the refresh button will update the table.
Can you try this?
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_database_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 & ";"
'& ";Uid=" & User_ID & ";Pwd=" & Password & ";"
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
Also, set a reference to Microsoft ActiveX Data Objects 2.8 Library (Tools > References).
Related
I have an Excel spreadsheet with several SQL queries stored in different cells and I'd like to execute these queries on SQL Server to generate a new sheet where each cell is the query result from the original spreadsheet. The idea behind this is to preserve the sheet formatting when generating the results (conditional formatting and etc.).
Something like this:
Input spreadsheet:
Database
Information A
Information B
DB 1
SQL Query 1
SQL Query 2
DB 2
SQL Query 3
SQL Query 4
Output spreadsheet:
Database
Information A
Information B
DB 1
Result of Query 1
Result of Query 2
DB 2
Result of Query 3
Result of Query 4
I wasn't able to find ideas on how to do exactly this during my research of the subject, but I do believe it should be doable using either VBA or some scripting language.
Any thoughts on how should I approach this?
I've got it done using Power Query. It was way easier than I thought. Special thanks to Jacek Wróbel for providing the idea in the comments.
As an aside, you could do something like this.
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 = "EXCEL-PC\SQLEXPRESS" ' Enter your server name here
Database_Name = "Northwnd" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM Orders" ' 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
With Worksheets("Sheet1").Range("A1:Z500")
.ClearContents
.CopyFromRecordset rs
End With
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
That sits in a VBA Module. Of course, you could store the SQL in an Excel cell, and do this...
SQLStr = Worksheets("Sheet1").Range("A1").Value
Also, you could loop through a bunch of cells and run a bunch of SQL jobs.
Your own imagination is your only limitation.
When I connect to Azure SQL database from MS Excel, I do not see the option to see stored procedures, I can see only tables and view for a chosen database. How do I execute a stored procedures to download results to excel?
Thanks for your time and help.
You can use Data-->Query to run the stored procedure in Azure SQL database from Excel.
Please follow my steps:
New Query-->From Azure-->From Azure SQL database:
SQL Server Database-->Advanced options-->Execute stored procedure statements:
Click OK--?choose Database to connect to Azure SQL-->See the result of stored procedure.
Then we can load the data into excel.
Note: I use Microsoft Office 2016 version.
I believe Azure Synapse is essentially the same as SQL Server, with a few minor differences. So, I'm not 100% sure that this will work, and I don't haccess to Azure now, but this will run a SPron sitting inside SQL Server.
Sub RunSProc()
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Set cn = New ADODB.Connection
strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Data Source=Your_Server_Name;"
strConn = strConn & "Initial Catalog=Your_Database_Name;"
strConn = strConn & "Integrated Security=SSPI;"
cn.Open strConn
Set cmd = New ADODB.Command
cmd.ActiveConnection = cn
cmd.CommandText = "MyOrders"
cmd.CommandType = adCmdStoredProc
cmd.Parameters.Refresh
cmd.Parameters(1).Value = ActiveSheet.Range("E1").Text
cmd.Parameters(2).Value = ActiveSheet.Range("E2").Text
Set rs = cmd.Execute()
If Not rs.EOF Then
Worksheets("sheet2").Range("A5:D500").CopyFromRecordset rs
rs.Close
End If
End Sub
If you want to make a request to SQL Server, and run any kind of SQL, you can do this.
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
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 = "NORTHWND" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT * FROM [Customers]" ' 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
For iCols = 0 To rs.Fields.Count - 1
Worksheets("Sheet1").Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
With Worksheets("sheet1").Range("a2: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
I am getting error while exporting data from SQL to already created .xlsx file. I used openrowset.
It works fine most of times, but when the data comes in of the field as a large string, while inserting in excel it shows error as:
the statement has been terminated , string or binary data would be
truncated.
Data gets inserted in table but while inserting in excel this error comes.
Please help me find the solution.
So, going form SQL Server to Excel, you can do many things. Check out thins link:
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction
Also, here is some VBA code to move data from SQL Server to Excel:
Sub ADOExcelSQLServer()
' Carl SQL Server Connection
'
' FOR THIS CODE TO WORK
' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library
'
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 = "EXCEL-PC\EXCELDEVELOPER" ' 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
I have been able in the past to create connections and pull in whole tables or even just a column or two from SQL into Excel.
Now what I want to for a user to input an ID into a Userform and then the VBA to run SQL code grabbing the cooresponding ID, FirstName, LastName. It should then paste that info into the first blank row of A,B,C on the "Entry" sheet.
I am getting an error on this line of code stating: Run-time error '1004' Application-defined or object-defined error.
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array("OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=xxx.xxx.xxx.xxx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DBName"), Destination:=Sheets("Entry").Range("A1").End(xlDown).Offset(1, 0)).QueryTable
Most of this I do not understand it is simply some hand me down code that I am trying to re-purpose. The old code which still works is this:
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=xxx.xxx.xxx.xxx;Use Procedure for Prepare=1;Auto " _
, _
"Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possibl" _
, "e=False;Initial Catalog=DBName"), Destination:=Range("Database!$A$1")). _
QueryTable
The difference between these is that instead of just dropping it in one set cell with the code pulling over couple hundred thousand lines of data is I want the code to be in the first blank row and only pull over that one record. But each time it runs it needs to go to the next row.
With the old code it made an actual table which I am guessing is related to the fact that at the end it states QueryTable. I would rather just have the data and not the table format. If there is a way to change it to do this that would be great.
Also in the previous version of this the query only pulled from one table and the .SourceConnectionFile = _ link to the file. The new code will need to link to two tables so there are two files as I was unable to have it make a connection file with two tables selected. If you can help with that as well that would be great.
I am using Excel 2013 Standard and SQL Server 2012. Please let me know if you need any more info.
So This is what I have so far trying the ADO method suggested by #Kyle. The OCR is the variable input from the Userform in previous code. When this runs it gives no error but it paste no data.
Sub Code()
Sheets("Entry").Select
On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Set objConnection = CreateObject("ADODB.Connection")
Set Objrecordset = CreateObject("ADODB.Recordset")
ConnectionString = "Provider=SQLOLEDB;Data Source=xxx.xxx.xxx.xxx;Initial Catalog=DBName;User ID=MyUN;Password=MyPW"
objConnection.Open
Objrecordset.Open "Select B.ID, B.Firstname, B.Lastname From TableA as A Join TableB as B on A.ID = B.ID Where A.Cardnumber =" & OCR, objConnection, adOpenStatic, adLockOptimistic, adCmdText
If Not Objrecordset.EOF Then
Sheets("Entry").Range("A1").End(xlDown).Offset(1, 0).CopyFromRecordset Objrecordset
Objrecordset.Close
Else
MsgBox "Did not Work"
End If
End Sub
So I was able to get it to work with this:
Sub Code()
Sheets("Entry").Select
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 = "" ' Enter your server name here
Database_Name = "" ' Enter your database name here
User_ID = "" ' enter your user ID here
Password = "" ' Enter your password here
SQLStr = "SELECT B.ID, B.FirstName, B.LastName From Table A Join Table B as B on A.ID = B.ID Where A.CardNumber ='" & OCR & "'" ' 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("Entry").Range("A1").End(xlDown).Offset(1, 0) ' 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
I need to find a value on a sql database.
I connected all tables in access and wrote a simple code to get the value.
Now I would like to extend it to all possible sql databases working with a connection string but select FROM MSysObjects is not working on sql.
Any suggestion?
Azienda = SOC(Y)
sConnString = "Provider=SQLOLEDB.1;User ID=sa;password=skipper;Initial
Catalog=" & Azienda & ";Data Source = server09;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096"
conn.Open sConnString
Dim TN(1000) As String 'NOME TAB
strsql = "SELECT MSysObjects.Name AS table_name FROM MSysObjects"
filtro = " WHERE Left([Name],1)<>'~' AND Left([Name],4)<>'MSys' AND MSysObjects.Type In (1,4,6) order by MSysObjects.Name"
Dim CF As ADODB.Field
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
With rst
.Open strsql & filtro, CONN, adOpenDynamic, adLockReadOnly