Saturday, February 25, 2012

Newbie - Querying SQL Server Express 2005 database from Excel

Sorry if this is a stupid question, but I created a database using SQl Server Express 2005 and I would like to query one of its tables from an Excel spreadsheet.

Here's what I want to do in pseudo code.

cell A2.value = select OLIGO_ID from table OLIGO where SEQUENCE = 'content of cell D2, a string'

In other words, I want to search the database for a string that is in a cell and retrieve its associated ID number into another cell. I need to do this on many cells.

Any help is appreciated. Thanks.

I guess you can do that with VBA.

As far as SQL is concerned I do something like that to extract data from a cube down to Excel. You will just have to build the connection string for SQL Express (get it from the macro recorder) and adjust the query to a more TSQL like query rather than OLAP. You can build any string you want.

Function to query SQL with a query string

-

Private Sub ado(Connection As String, Query As String, destination As String)
Dim cnnConnect As ADODB.Connection
Dim rstRecordset As ADODB.Recordset

Set cnnConnect = New ADODB.Connection
cnnConnect.Open Connection

Set rstRecordset = New ADODB.Recordset
rstRecordset.Open _
Source:=Query, _
ActiveConnection:=cnnConnect, _
CursorType:=adOpenDynamic, _
LockType:=adLockReadOnly, _
Options:=adCmdText

With ActiveSheet.QueryTables.Add( _
Connection:=rstRecordset, _
destination:=Range(destination))
.FieldNames = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
cnnConnect.Close
Set cnnConnect = Nothing
Set rstRecordset = Nothing
End Sub

-

-- OLAPMENU

OlapMenu = _
"Provider=MSOLAP;Integrated Security=SSPI;Persist Security Info=False;Location=analysis.onsemi.com;Initial Catalog=" & InitialCatalog & ""

--

call to the function

Query = "select" & _
"[data Switch].[Switch].members on axis(0)," & _
" Filter( [Region].[Rep Sales Region Desc].members, [Data Switch].[On] >0 ) on axis(1)" & _
"from [ST_Crawl]"
Application.StatusBar = "Now Populating Pull-down Region, please wait..."
Application.Cursor = xlWait
Call ado(OlapMenu, Query, "A3")

|||Yes, I would go as far as say write a function in Excel that accepts the input parameter, then uses ADO to fetch the data. Then you can pass in the value from the spreadsheet into the function, the function takes the parameter and uses an ADODB.Command with params to execute the SQL statement, then the function returns the output as a string.

No comments:

Post a Comment