问题
I'm having trouble getting a field of LONG
out of the database and into my Excel (VBA + ADO) application. I wonder if anyone could help?
Doing this has no effect at all (casting to a string, or not):
myString = dataset!long_field
I tried the GetChunk
method, which is supposed to do what I'm hoping:
myString = CStr(dataset!long_field.GetChunk(1000))
This does get something, but it's not the data I'm expecting (it's usually some garbled mess). What's weird is that, if I try running this in the Immediate window, while I'm stepping through the code, I get something hopeful:
Debug.Print CStr(dataset!long_field.GetChunk(1000))
e l l o W o r l d !
I don't know why it (sort of) works in the Immediate window and not elsewhere. Also of note:
Oracle seems to be using some kind of 2-byte encoding, so there's the weird spacing
A chunk of the data from the beginning is missing; this should read "Hello World!"
My other plan of attack was to write a function on the database side to convert long
to varchar2
. Unfortunately, this also failed because the table I need to access is outside my schema and I don't have the appropriate grants to select the data from a function (Oracle complains that the table is not found).
So I'm kind of lost :( Any ideas?
回答1:
This works for me:
Debug.Print BinaryToString(RS.Fields("long_raw").Value)
Where "RS" is an ADO recordset containing query results and "BinaryToString" is as shown below.
Function BinaryToString(Binary)
'Antonin Foller, http://www.motobit.com
'Optimized version of a simple BinaryToString algorithm.
Dim cl1, cl2, cl3, pl1, pl2, pl3
Dim L
cl1 = 1
cl2 = 1
cl3 = 1
L = LenB(Binary)
Do While cl1 <= L
pl3 = pl3 & Chr(AscB(MidB(Binary, cl1, 1)))
cl1 = cl1 + 1
cl3 = cl3 + 1
If cl3 > 300 Then
pl2 = pl2 & pl3
pl3 = ""
cl3 = 1
cl2 = cl2 + 1
If cl2 > 200 Then
pl1 = pl1 & pl2
pl2 = ""
cl2 = 1
End If
End If
Loop
BinaryToString = pl1 & pl2 & pl3
End Function
回答2:
Turns out that GetChunk
does work: I did some sandbox testing and, while there's still the weird encoding, it does return all the data I want. As such, I don't know why the data is getting garbled in my main query; so my solution is to just use a function that gets the long data -- and decodes it -- and call this when needed, rather than including the data in the main query.
来源:https://stackoverflow.com/questions/7980483/extract-oracle-long-to-string-in-vba