Is there a limit to the query length being passed to ADODB? - sql

I am currently testing a framework that stores a SQL query in a cell on an excel workbook and then passes the cell value to a variable. This variable then gets executed through rs.Open query, cn where:
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
and I have tried these for "query" :
Dim query as String
Dim query as Variant
or even playing with fixed length queries:
Dim query as String * 9999
In playing with the output of the query string, it cuts off somewhere around 8000. Google is coming up short for me, so I am coming here for answers. Is there a specific limit to what a variable can pass to recordset.Open()?
NB: The connection string I am using for this particular query is :
ConnectionString = "User ID=User;Password=PW;Data Source=DB;Provider=OraOLEDB.Oracle"
But if you know whether there is a system specific limit for Oracle, NetezzaSQL, or MS SQL Server (SQLOLEDB.1) please let me know. I will need to specify the limitations of each in order to define which new queries will need to be converted into stored procedures.
Here is the essentials of the code:
Sub RunQueryTable()
Dim cn As ADODB.Connection
Dim RS As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String
Dim SQLTable As Worksheet
Dim ConnectionString as String
Dim query As String 'Or Dim query As Variant 'Or Dim query As String * 9999
Dim i As Long
etc, etc.
Set SQLTable = Sheet32
Set cn = New ADODB.Connection
Set RS = New ADODB.Recordset
DB = _____
User = ______
PW = ____
ConnectionString = "User ID=" & User & _
";Password=" & PW & _
";Data Source=" & DB & _
";Provider=OraOLEDB.Oracle"
query = SQLTable.Cells(i, 3).Text
cn.Open (ConnectionString)
RS.CursorType = adOpenForwardOnly
RS.Open (query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Output").Cells(1, iCols + 1).Value = RS.Fields(iCols).Name
Next
Worksheets("Output").Cells(2, "A").CopyFromRecordset RS
RS.Close
cn.Close
End Sub
The specific error I am getting from VBA is : "ORA-00923: FROM keyword not found where expected" because the query is getting cut off.

Here's your problem:
query = SQLTable.Cells(i, 3).Text
Consider:
Range("A1").Value=string(12000,"*")
? len(range("a1").value) '>> 12000
? len(range("a1").text) '>> 8221

Related

VBA(AUTOCAD) SQL query to store String Values

I have a small issue, I am trying to code a Macro for Autocad in VBA.
I am trying to read a certain column value through sending a SQL native query that connects to the database server.
The problem is that my String variable descToReturn that's going to hold a value of that column is returning null. I can't seem to figure out where I am wrong. So if anyone can advise that'd be great.
Here's the code below:
Private Sub btnDuplicate_Click()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim BOMLineToCheck As AcadBlockReference
Dim BOMAttributes As Variant
Dim partNoToCheck As String
Dim i As Integer
Dim descToReturn As String
ConnectionString = "Provider=SQLxxxxx.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Data Source=xx\xx;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=xxx_xxx"
Set cnn = New ADODB.Connection
cnn.ConnectionString = ConnectionString
cnn.Open
'cnn.CommandTimeout = 900
Set rst = New ADODB.Recordset
StrQuery = "SELECT * FROM [My Table Name] WHERE [My Column]='partNoToCheck'"
For Each BOMLineToCheck In ThisDrawing.ModelSpace
If BOMLineToCheck.Name = "BOM3LINE_old" Then
BOMAttributes = BOMLineToCheck.GetAttributes()
For i = 0 To UBound(BOMAttributes)
If BOMAttributes(i).TagString = "PART#" Then
partNoToCheck = BOMAttributes(i).TextString
End If
Next i
End If
rst.Open StrQuery, cnn, adOpenDynamic
With rst
If Not .EOF Then
descToReturn = rst![My Coulmn]
End If
End With
rst.Close
MsgBox descToReturn
Next
End Sub
Look closely for a typo:
descToReturn = rst![My Coulmn]
You probably mean:
descToReturn = rst![My Column]
See the difference?
So, I found the answer, because I am bringing SQL within VBA environment, the syntax was not right and its a weird syntax:
correct Syntax for SQL query:
StrQuery = "SELECT * FROM [My Table] WHERE [My Column]= '" & partNoToCheck & "'"

excel vba to run a sql command getting selected data from a CSV file

I am trying to run a sql command based on a selected org name from a drop down list , then import all the matching rows from a csv file that have the same org name , I can get it working with a ODBC connection , but it does not work when changing it to a CSV connection , any help would be much appreciated
Public Const ConnStringCSV = "Microsoft.Jet.OLEDB.4.0" & _
"Data Source=T:\DataFeed;" & _
"Extended Properties=""text;HDR=yes;FMT=Delimited(,)"";Persist Security Info=False"
im conn As New ADODB.Connection
Sub import_from_csv()
Dim conn As New ADODB.Connection
Dim connMasterConnection As New ADODB.Connection
Dim rsObj As New ADODB.Recordset
Dim Ws_FData As Worksheet
Dim Ws_UserForm As Worksheet
Dim strSQL As String
Dim org as String
Dim iCols As Integer
Dim varname1 As String
Dim ops As String
Set Ws_Fdata = ActiveWorkbook.Worksheets("FData")
'Delete the last results before we start the new run
Ws_FData.Cells.Clear
'The value of the organisation that the users chooses
org = Sheet5.Range("A1").Value
connMasterConnection.Open ConnStringCSV
'varname1 is the SQL Code I need to look for a match in org name from a
'search 'list I have , then add all the rows of data
'The CSV File is called OrgCheck.csv
rsObj.Open varname1, connMasterConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
For iCols = 0 To rsObj.Fields.Count - 1
Ws_FData.Cells(1, iCols + 1).Value = rsObj.Fields(iCols).Name
Next
Ws_FData.Range("A2").CopyFromRecordset rsObj
connMasterConnection.Close`enter code here`
There's a missing semi-colon. It should be:
Public Const ConnStringCSV = "Microsoft.Jet.OLEDB.4.0;" & _

Error while storing records from Access field in array

Situation :
I have this code which stores all the records from the field Shipment ID in an array called arrayShipmentID.
Dim conn As New ADODB.Connection
Dim connStr As String
Dim rs As ADODB.Recordset
Dim ShipmentIDSQL As String
Dim arrayShipmentID() As Variant
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "P:\PathToTheAccessDatabase\" & "NewVersion.accdb" & ";"
conn.ConnectionString = connStr
conn.Open
' Store Shipment IDs
Set rs = New ADODB.Recordset
ShipmentIDSQL = "SELECT [Shipment ID] FROM 12Dec"
rs.Open ShipmentIDSQL, conn, adOpenStatic, adLockReadOnly, adCmdText
If Not rs.EOF Then
arrayShipmentID = rs.GetRows
End If
Dim i As Integer
For i = 0 To UBound(arrayShipmentID, 2)
Debug.Print arrayShipmentID(0, i)
Next i
Set rs = Nothing
In order to make sure it works I Debug.Print each element of the array.
Issue :
This code WORKS most of the time, but for some reason, sometimes I get as a value 'subscript out of range' (instead of 181 in my case) for MsgBox UBound(arrayShipmentID, 2) and of course in that case Debug.Print doesn't display anything in the Immediate Window.
Any ideas where could this come from ?
With DAO recordsets you often have to find the recordcount to retrieve all records. That might be the case for ADO as well:
RecordCount = ' Obtain true count of records.
arrayShipmentID = rs.GetRows(RecordCount)
Also, I normally declare the variable as a simple Variant:
Dim arrayShipmentID As Variant

Changing of DSN in VBA

I am trying to change the connection of the excel from JDE to SQL Server 2014. How/What should i do/change in order to connect to another DSN in my ODBC.
This is my code for cnnStr:
uid = Range("P_Uid")
pwd = Range("P_Pwd")
dsn = Range("P_Dsn")
cnnstr = "ODBC;DSN=" + dsn + ";UID=" + uid + ";PWD=" + pwd
This is the original code from VBA:
Dim strCnn As String
Dim i As Long
Dim y As Long
Dim j As Long
Dim z As Double
Dim w As Double
Dim Wks As DAO.Workspace
Dim Cnn As DAO.Connection
Dim Qdf As DAO.QueryDef
Dim Rec As DAO.Recordset
Dim date1, date2 As String
Dim x As Long
Dim w_price As Double
Dim w_amt As Double
Dim w_qty As Long
Dim Xref_Name(10) As Variant
Set Rec = Nothing
Set Wks = CreateWorkspace("WKSTmp", "", "", dbUseODBC)
Set Cnn = Wks.OpenConnection("", dbDriverNoPrompt, True, cnnstr)
Cnn.QueryTimeout = 1800
Set Rec = Cnn.OpenRecordset(SQL)
avarow = Worksheets("Ava").UsedRange.Rows.Count
Whenever i mouse over to cnnstr, i will see this code :
cnnstr = "ODBC;DSN=JDE;UID=abc;PWD=abc"
The DSN is always JDE even though i have tried to change the connection and the cnnStr above.
The details of the cnnstr is taken from a control sheet within the excel file. Changes made to the control sheet proved futile.
Please advice on how I can change the dsn so that I can get the data from SQL Server 2014.
This is what I use use to connect to SQL server 2014,
Code,
Sub ConnectSQLServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "PROVIDER=SQLOLEDB;" & _
"Data Source=xxx.xxx.x.xxx,1433;" & _
"Initial Catalog=Staff_Manager;" & _
"User Id=sa;" & _
"Password=myPassword;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs.ActiveConnection = conn
Set rs.ActiveConnection = conn
strSQL = "SELECT Your SQL Statement "
rs.Open strSQL
If that is what you are trying to achieve this will work.
Assuming you didn't leave out anything important from your original code, cnnstr is neither a local declared variable, nor is it assigned in that routine. Most likely you either have a cnnstr() function or it's a global variable being set in the CreateWorkspace() function.
The simplest way to find where the code is still assigning the old connection string to cnnstr is to use Find to search the Current Project for "cnnstr =". (Minus the quotes.) Make sure you are searching Current Project in case the assignment is happening in a different module.

Use SQL Statement in access 2007 [duplicate]

What's wrong with this code:
Visual Basic 6.0 With access 2007
Private Sub Command1_Click()
Dim Sell_tbl, Stock_Bottle, res As String
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
res = ((Sell_tbl) - (Stock_Bottle))
Adodc1.RecordSource = Sell_tbl
Adodc1.Refresh
Adodc1.Caption = Adodc1.RecordSource
End Sub
Type Mismatch Error
I try to convert its result in other data type but it doesn't work. Can anyone help me?
Neither of these is a recordset, each is a string:
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
You need something on the lines of:
Dim Sell_tbl As DAO.Recordset
Dim Stock_Bottle As DAO.Recordset
Set Sell_tbl = CurrentDB.Openrecordset _
("SELECT Sum((Quantity)*12) As Qty FROM Sell_Detail Where Cateogry='Large'")
Set Stock_Bottle = CurrentDB.Openrecordset _
("Select Sum(No_Of_Bottle) As Btl FROM Add_Bottle Where Cateogry='Large'")
res = Sell_tbl!Qty - Stock_Bottle!Btl
The above is a rough outline, it could do with tidying up.
The reason for the error is because of statement:
s = ((Sell_tbl) - (Stock_Bottle))
If you look above that line, you are setting two string variables to SQL -- which is text not numeric.
You need to open recordsets with those sql strings, then get the results, then perform the math.
It is what I want....
Private Sub Command2_Click()
Dim con As New ADODB.Connection
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& App.Path & "\add_entry.mdb;Persist Security Info=False"
Dim rs As New ADODB.Recordset
Dim rs1 As New ADODB.Recordset
Dim result_hold As Integer
Dim large_tbl As String
Dim sell_large As String
large_tbl = "SELECT Sum(No_Of_Bottle) FROM add_cotton where Cateogry='Large'"
sell_large = "SELECT Sum(Quantity) FROM Sell_Detail where Cateogry='Large'"
rs.Open large_tbl, con, adOpenDynamic, adLockOptimistic
rs1.Open sell_large, con, adOpenDynamic, adLockOptimistic
result_hold = CInt(rs.Fields(0).Value) - CInt(rs1.Fields(0).Value)
Text1.Text = CStr(result_hold)
End Sub
'if u need to retreive whole colum use loop or etc.. but one thing is remember to you two sources
'never attach with single grid...