SQL too long for String - sql

I have the following SQL to be queried. It is a valid SQL. Unfortunately, it is too long for a string in VBA. Anyone knows of a workaround to run this query?
SQL = "SELECT A.cust_ky, A.incid_id, A.OPEN_TS, A.CLOSE_TS, A.REC_UPD_TS, B.wrkgp_id, A.CURR_AGNT_KY, A.incid_ttl_dn " _
& "FROM (MAINTBLS.INCID_FAB A INNER JOIN MAINTBLS.DEPTMNT B ON A.curr_wrkgp_ky=B.wrkgp_ky) " _
& "WHERE B.wrkgp_id='" & wrkgp & "' And (A.open_fg = 1 OR A.pend_fg = 1)" _
& "ORDER BY A.cust_ky, A.curr_agnt_ky ASC"
rs.Open SQL, con, adOpenKeyset

Since you use Oracle, you should use a bind variable instead of dynamic SQL and then set the value in the parameter collection of the command object. Not only will it prevent SQL Injection, but it will better optimize your query.
Also, it looks like your SQL Statement is missing a space before the order by clause. That could easily cause your error. See below - untested, but should give you the idea.
SQL = "SELECT A.cust_ky, A.incid_id, A.OPEN_TS, A.CLOSE_TS, A.REC_UPD_TS, B.wrkgp_id, A.CURR_AGNT_KY, A.incid_ttl_dn " _
& "FROM (MAINTBLS.INCID_FAB A INNER JOIN MAINTBLS.DEPTMNT B ON A.curr_wrkgp_ky=B.wrkgp_ky) " _
& "WHERE B.wrkgp_id= :wrkgp And (A.open_fg = 1 OR A.pend_fg = 1) " _
& "ORDER BY A.cust_ky, A.curr_agnt_ky ASC"
With cmd
.ActiveConnection = conn
.CommandText = SQL
.CommandType = adCmdText
.Parameters.Append .CreateParameter(, adVarChar, adParamInput, wrkgp)
End With

Create a view for the query, something like this
create view fix_for_broken_vba as
SELECT A.cust_ky, A.incid_id, A.OPEN_TS, A.CLOSE_TS, A.REC_UPD_TS, B.wrkgp_id,
A.CURR_AGNT_KY, A.incid_ttl_dn FROM (MAINTBLS.INCID_FAB A INNER JOIN MAINTBLS.DEPTMNT B ON A.curr_wrkgp_ky=B.wrkgp_ky)
WHERE (A.open_fg = 1 OR A.pend_fg = 1)
and then rewrite the query accordingly.

If you are using VBA in an Excel sheet, why don't you consider putting the SQL query in a protected cell of your document? You could even put it in an hidden sheet of your document.
Something like:
Cells(6, 2).Select
sqlString = Cells(6, 2).Value
I did it and it works like a charm in my case.

I've used the following steps for a 100+ line query
Use a long Query with Excel VBA
Initially create the query in SSMS
Create a sheet called SQL Query
Copy and paste the query in to the SQL Query sheet and delete all rows that are blank or commented row
Incorporate any variables in to the declare statement
Use the following macro to loop through the SQL Query sheet
LastRowQ = ThisWorkbook.Sheets("SQL Query").Cells(ThisWorkbook.Sheets("SQL Query").Rows.Count, "B").End(xlUp).Row
Count = 2
Do Until Count > LastRowQ
SQLQTemp = ThisWorkbook.Sheets("SQL Query").Range("B" & Count)
SQLQuery = SQLQuery & " " & SQLQTemp
Count = Count + 1
Loop
SQLDatabaseRS.Open SQLQuery

Related

Query causes UPDATE syntax error, when 'where-attribute' is a date

Whenever i try to update a table in the SQL-Database via excel-vba using a Date-formated primary key as the
'where-attribute', a syntax error appears while executing the SQLQuery; in my example: wrong syntax near ".1900".
However, when i create a table in sql using the 1900er number-format to express dates(as excel saves dates: 1 = 01.01.1900; 2 = 02.01.1900 etc.), format the date-column according to that in my excel-sheet, which shall be used to update the table in SQL, and run the exact same code, no error appears and the SQL-table gets updated. Here is an extract of my used code.
strWhere = "[Date] = " & strDate
SQLQuery = "update " & TableNameSql & " " & _
"set " & _
"[Column1Data] = '" & strColumn1Data & "' " & _
"Where " & strWhere
the debug.print of the SQLQuery for both options look as following:
update TableNameSql set [Column1Data] = '-0,1149' Where [Date] = 02.01.1900 'Error
update TableNameSql set [Column1Data] = '-0,1149' Where [Date] = 2 'no Error
I believe it may have to do with the dots in the date(strWhere).
It could also be, that the Problem accurs because of different language settings in excel and SQL-Server. However, creating tables and exporting data from SQL to Excel is no Problem.
I've found different similar questions asked, however, none of the answers suited my specific problem.
Using the 1900er-Date-Format is also not useful in practice, so i would like to get this error fixed while using regular dates.
Consider using the ISO date format as YYYY-MM-DD which you can format using VBA's Format() assuming strDate is a VBA Date type. Also, be sure to enclose in single quotes.
strWhere = "[Date] = '" & Format(strDate, "YYYY-MM-DD") & "'"
Even better consider parameterization and avoid any quotation or concatention such as ADO command which allows you to align data types:
' PREPARED STATEMENT WITH QMARKS
SQLQuery = "UPDATE " & TableNameSql & " " & _
"SET [Column1Data] = ? " & _
"WHERE [Date] = ?"
' ... LOAD ADO CONNECTION ...
Set cmd = New ADODB.Command
With cmd
.Activeconnection= conn
.CommandText = SQLQuery
.commandType = adCmdText
' BIND PARAMS
.Parameters.Append .CreateParameter("StrParam", adVarChar, adParamInput, 255, strColumn1Data)
.Parameters.Append .CreateParameter("DateParam", adDate, adParamInput, , strDate)
' RUN ACTION QUERY
.Execute()
End With

Executing a SQL query from vba results with nothing

Cheers,
I am trying to send a simple SQL query, but I get no results in my recordset as if it simply was not executed.
Just after, I am executing a different query, which results correctly.
When running the same query from SMSS, do brings up the desired results.
Following is the code:
If CheckLogsFromRestartDay = True Then
'This line does NOT seem to work. Nothing is changed in the Recordset
Set objMyRecordset = objMyConn.Execute( _
" SELECT top 1 cast(tValue AS date) AS RestartDate " & _
" FROM settings (nolock) WHERE tkey = 'EngineStartTime' ")
'This line DOES provide an answer correctly
Set objMyRecordset = objMyConn.Execute( _
" SELECT * FROM " & LogTable & " (nolock) where Webpage like 'Engines%'" & _
" ORDER BY id desc")
sTodayMMDD = objMyRecordset!RestartDate
Else
sTodayMMDD = Format(Date, "yyyy-mm-dd")
End If

Store a sql select statement, ran from VBA, in a numeric variable

I'm working on creating a dynamic pass-through query and in order to do so I first need to query my local db and get an ID.
This ID is what I will put into my pass-through query for my WHERE clause of the query.
My string:
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
I'm then trying to do something akin to:
CorpID (integer) = docmd.runsql (getCorpID)
I realize, however that docmd runsql doesn't work with select statements, or return a value even. What can I use to run my string
getCorpId
as sql and store the result (It will only be one result, every time.. one number) in my variable CorpID
Thank you.
Consider about using Recordset :
Dim dbs As DAO.Database
Dim rsSQL As DAO.Recordset
Dim getCorpID As String
Dim CorpID
Set dbs = CurrentDb
getCorpID = "SELECT corpID " & _
"FROM dbo_corp " & _
"WHERE name = " & Forms.frmMain.Combo4.Value
Set rsSQL = dbs.OpenRecordset(getCorpID , dbOpenSnapshot)
rsSQL.MoveFirst
CorpID = rsSQL.Fields("corpID")

Joining Tables with MYSQL queries in VBA (excel)

I am completely new to Visual Basic. I am working with a MYSQL data base and I want to use VB in excel so I can work with more complex queries. For some reason, when I try to join tables in vb, I get an error message. Can somebody tell me what is wrong with my code.
strSql = "SELECT COUNT(*)FROM `order`" & _
"JOIN user ON user.id = order.destination_id" & _
"WHERE payment_status = 'pay';"
rs.Open strSql, oConn, adOpenDynamic, adLockPessimistic
res = rs.GetRows
rs.Close
Range("A1", "A6") = res(0, 0)
your current query will produce this string,
SELECT COUNT(*)FROM `order`JOIN user ON user.id = order.destination_idWHERE payment_status = 'pay';
^ ^ ^
you lack space during your concatenation, in order to correct that, simply add space before double quote.
strSql = "SELECT COUNT(*) FROM `order` " & _
"JOIN user ON user.id = order.destination_id " & _
"WHERE payment_status = 'pay';"

Syntax Error in From clause Deleting record with ADO

I'm using ADO to delete a record in my MS Access 2007 database and am at a total loss as to why I'm getting this syntax error for my SQL code. It claims there is an error in the FROM clause but I do not see it. I have taken the FROM clause directly from a working SQL statement in another module using the same table. I've entered the code into the SQL View of a new query and it runs just fine. Here is the code:
Private Sub cmdDeleteMessage_Click()
If MsgBox("Once you delete a message, it cannot be undone." & _
"Are you sure you want to delete this message?", vbYesNo) = vbYes Then
Dim sql As String
Dim rsDel As New ADODB.Recordset
rsDel.CursorType = adOpenDynamic
rsDel.LockType = adLockOptimistic
sql = "DELETE * FROM [Staff Notes] WHERE [MsgID] = " & Me.txtMsgID.Value & ";"
rsDel.Open sql, CurrentProject.AccessConnection, , , adCmdTable
With rsDelete
.Update
.Close
End With
End If
End Sub
And Ideas? Thanks in advance!
You're trying to run an action query but using a recordset (which expects a select query).
Try this:
sql = "DELETE * FROM [Staff Notes] WHERE [MsgID] = " & Me.txtMsgID.Value & ";"
CurrentProject.AccessConnection.Execute sql, , adExecuteNoRecords
Also, if [MsgID] is a string, you need to enclose your value in quotes:
sql = "DELETE * FROM [Staff Notes] WHERE [MsgID] = " & Chr$(34) & Me.txtMsgID.Value & Chr$(34) & ";"