Best way to perform an Oracle query on a cell?
I have an Excel spreadsheeet with a cell containing a concatenated name and surname (don't ask why). For example, Cell A2: BLOGGSJOE
.
On this cell, I would like to run the following SQL and output it to cell A3, A4 and A5:
SELECT i.id, i.forename, i.surname FROM individual i WHERE UPPER(REPLACE('" & A2 & "', ' ', '')) = UPPER(REPLACE(i.surname|| i.forename, ' ', '')) AND NVL(i.ind_efface, 'N') = 'N'
Any idea how I could perform an Oracle query on each cell and return the result?
I have enabled an Oracle datasource connection in Excel, just not sure what to do now.
Is this a stupid approach, and can you recommend a better more proficient way?
I am aware that I could just write a simple Ruby/PHP/Python/whatever script to loop through the Excel spreadsheet (or 开发者_JAVA百科.csv file) and then perform the query etc. but I thought there might be a quick way in Excel itself.
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Set cn = New ADODB.Connection
cn.ConnectionString = 'Get one from http://www.connectionstrings.com/oracle
'eg. "Driver={Oracle in OraHome92};Dbq=tns;Uid=uid;Pwd=pwd;"
cn.Open
sql = Your SQL
Set rs = cn.Execute(sql)
for loop or something to paste records
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
if you format your spreadsheet properly you could assign rs to a Variant and then assign the variant to a range instead of looping through it.
Edit
With your current SQL you would need to loop through each cell and query the db, then save the results to A3:A5. Edit 2, Something like that:
Private Function GetRow(user As String) As Variant
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Dim v As Variant
Set cn = New ADODB.Connection
cn.ConnectionString = "Driver={Oracle in OraHome92};Dbq=tns;Uid=uid;Pwd=pwd;"
cn.Open
sql = "SELECT i.id, i.forename, i.surname FROM individual i WHERE UPPER(REPLACE('" & user & "', ' ', '')) = UPPER(REPLACE(i.surname|| i.forename, ' ', '')) AND NVL(i.ind_efface, 'N') = 'N'"
Set rs = cn.Execute(sql)
v = rs.GetRows()
GetRow = v
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Function
Sub a()
Dim user As String
For i = 2 To x
user = ActiveSheet.Cells(i, 1).Value
GetRow (user)
ActiveSheet.Cells(i, 2).Value = GetRow(0)
ActiveSheet.Cells(i, 3).Value = GetRow(1)
ActiveSheet.Cells(i, 4).Value = GetRow(2)
Next
End Sub
Note that I have used different cells that you wanted and the GetRow is 2D not 1D, but is hard for me to write it up with no access to actual spreadsheet/db
Pls check my answer here. Using that code, you can call your Oracle query (recursively or not). I think it would be faster to:
- first build a list of items to be retrieved (BLOGGSJOE, JOEBAR, JUSTINCASE)
- then retrieve your Oracle data in a separate list using IN (BLOGGSJOE, JOEBAR, JUSTINCASE) as your criteria
- finally make a lookup in Excel on that newly downloaded list
精彩评论