Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pulling Column Names into Excel from SQL query

I'm using Excel to pull data from an SQL db. I used the code from another SO question and it works fine. Now I want to pull in the column names from a table in addition to the actual table. I figured out that I could get the names using the For Each fld loop. However there's still the issue of populating them horizontally in a row in Excel as the number of columns might change - so I'm thinking I would need another For each loop also or something similar.

Sub GetDataFromADO()

'Declare variables'
    Set objMyConn = New ADODB.Connection
    Set objMyCmd = New ADODB.Command
    Set objMyRecordset = New ADODB.Recordset

'Open Connection'
    objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"
    objMyConn.Open

'Set and Excecute SQL Command'
    Set objMyCmd.ActiveConnection = objMyConn
    objMyCmd.CommandText = "select * from myTable"
    objMyCmd.CommandType = adCmdText
    objMyCmd.Execute

'Loop Names'
    ' WHAT TO DO HERE????'

'Open Recordset'
    Set objMyRecordset.ActiveConnection = objMyConn
    objMyRecordset.Open objMyCmd

'Copy Data to Excel'
    ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)

End Sub
like image 827
firedrawndagger Avatar asked Nov 16 '10 01:11

firedrawndagger


People also ask

How can I get column names from a table in SQL query?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'

How do I list all columns in SQL?

In a query editor, if you highlight the text of table name (ex dbo. MyTable) and hit ALT + F1 , you'll get a list of column names, type, length, etc.


1 Answers

My usual code is very similar:

For intColIndex = 0 To objMyRecordset.Fields.Count - 1 
    Range("A4").Offset(0, intColIndex).Value = objMyRecordset.Fields(intColIndex).Name
Next
like image 57
dendarii Avatar answered Oct 07 '22 10:10

dendarii