Expected function / variable error message - sql

i am trying to write a simple append query using SQL for my access database. Upon trying to execute the code, the message i am getting is:
Complilation error. Exepected function or variable
The query is a query which joins 4 tables and pastes the fields into another table. When using a standard MS Access query it works fine. I then generated and copied the SQL code (below) but unfortunately cannot get the query to work.
A final note about something strange. Unlike all the other SQL queries i have successfully written, this one, upon writing the Application.DoCmd.RunSQL (st_sql) into VBA, the space between the "L" and the "(st_sql) for some reason gets truncated.. Strange, this doesnt happen for any other string in the Whole routine where i successfully have other append queries.
Below is the code:
st_sql = "INSERT INTO[tblContactReporting03]([ID Project],[tblProjManagementPhaseHierarchy],[tblProjManagementSubPhaseHierarchy],[ID_Event],[SubTask_Hierarchy],[Project],[Sub project],[Project_Phase],[Project_Sub_Phase],[ContactFullName],[Role_Type],[type],[Event],[Effective_date],[Commitment],[Sub_task_name],[Status],[Notes])" & _
"SELECT[tblProjectMasterList].[ID Project],[tblProjManagementPhase].[Hierarchy],[tblProjManagementSubPhase].[Hierarchy],[tblContactReporting02].[ID_Event],[tblContactReporting02].[SubTask_Hierarchy],[tblProjectMasterList].[Project],[tblProjectMasterList].[Sub project],[tblProjManagementPhase].[Project_Phase],[tblProjManagementSubPhase].[Project_Sub_Phase],[tblContactReporting02].[ContactFullName],[tblContactReporting02].[Role_Type],[tblContactReporting02].[type]," & _
"[tblContactReporting02].[Event], [tblContactReporting02].[Effective_date],[tblContactReporting02].[Commitment],[tblContactReporting02].[Sub_task_name],[tblContactReporting02].[Status],[tblContactReporting02].[Notes]" & _
"FROM[tblProjectMasterListINNER JOIN ([tblProjManagementPhase] INNER JOIN ([tblContactReporting02] INNER JOIN [tblProjManagementSubPhase] ON [tblContactReporting02].[ID_Project_Sub_Phase] = [tblProjManagementSubPhase].[ID_Project_Sub_Phase]) ON ([tblContactReporting02].[ID_Project_Phase] = [tblProjManagementPhase].[ID_Project_Phase]) AND ([tblProjManagementPhase].[ID_Project_Phase] = [tblProjManagementSubPhase].[ID_Project_Phase])) ON [tblProjectMasterList].[ID Project] = [tblProjManagementPhase].[ID_Project]" & _
"ORDER BY [tblProjectMasterList].[ID Project], [tblProjManagementPhase].[Hierarchy], [tblProjManagementSubPhase].[Hierarchy], [tblContactReporting02].[ID_Event], [tblContactReporting02].[SubTask_Hierarchy];" & _
Application.DoCmd.RunSQL(st_sql)

I'd recommend a Debug.Print st_sql before running so that you'll be able to debug the constructed SQL.
The error you're getting is because RunSQL is a sub, not a function, so you need to call it 1) without parentheses:
Application.DoCmd.RunSQL st_sql
or 2) preceed it with Call and use parentheses:
Call Application.DoCmd.RunSQL(st_sql)
You can use syntax 2 for functions that when you don't need to use their return value.

Related

How to run an SQL query via VBA where the query is stored in an Excel cell?

I am trying to run an SQL query via VBA where the query is stored in an Excel cell. The images show the VBA code, which works perfectly as long as the query dont contain aggregated functions with a group by clause at the end. The last part of the codes that works refer to "mydate" which is a defined variable in my Excel spreadsheet, and the query will then run for that date via "where value_date= . The string in VBA is defined as this: Src = Worksheets("Cash-renter oversikt").Range("AX2").Value & "'" & myDate & "'".
Picture of the VBA code
When i try to write a query with aggregated functions and include a group by clause at the end of the query, which is stored in the excel cell, i get an error message: "incorrect syntax near the keyword group". My theory is that VBA is only able to read the query up until the "where value_date= and the reference to "mydate". How can i change the VBA code so that is able to read the group by clause in the sql query?
Picture of the SQL query stored in Excel cell AX2
Enter the GROUP BY line in a separate cell so you can append it after myDate. For example using AY2.
With Worksheets("Cash-renter oversikt")
Src = .Range("AX2").Value & "'" & myDate & "' " & .Range("AY2").Value
End With

Run one MS Access SQL script on a particular Table chosen by user

I have a MS Access 2016 database (*.accdb) with 20+ Tables. Fields in each of them vary slightly from Table to Table. I've no VBA experience, so I'm sticking only to the SQL query below (redacted).
SQL script
myvar below is the parameter I'd like to be prompted when the script is run so that I enter the Table I want the changes applied to.
PARAMETERS
[myvar] TableID;
UPDATE
[myvar]
INNER JOIN
Excel_Data ON [myvar].[Part Number] = Excel_Data.[Part Number]
SET
[myvar].[Value] = '?',
[myvar].Description = Excel_Data.Description,
[myvar].[Ref] = '?'
.
.
.
WHERE
[myvar].Description Is Null;
Output
Error message:
Too few parameters. Expected 0.
What I need
I prefer a solution for above in a SQL script form as above, not involving VBA, preferably. I'd like to enter the Table name when prompted so the script knows which table to UPDATE. FYI: The PARAMETERS work when it is not a Table as I've shown in my script above.
Help/advise is highly appreciated.
EDIT 1
Since it seems not possible to use parameters as Table names, could you suggest a VBA solution? A sample code, perhaps?
As said in the comments, you can't really solve this without VBA.
You can store your SQL query in a string, and use a placeholder to indicate the tablename. Then get the tablename using an inputbox and replace the placeholder with the tablename.
Dim sqlString As String
sqlString = "UPDATE [%Placeholder%] " & vbCrLf & _
"INNER JOIN Excel_Data ON [%Placeholder%].[Part Number] = Excel_Data.[Part Number] " & vbCrLf & _
"SET [%Placeholder%].[Value] = '?', " & vbCrLf & _
...
"WHERE [%Placeholder%].Description Is Null;"
sqlString = Replace(sqlString, "%PlaceHolder%", InputBox("Enter a tablename"))
CurrentDb.Execute sqlString
In a more mature solution, I'd create a form with a combobox containing all available table names, and add a function to sanitize tablenames (replace "]" with "]]")

to use module in sql ms-Access-2010

I have defined a procedure in my module, returning the path of the database and I want to use that path in my sql query.
Procedure in module :
Public Function pathOfBillingSoftware() As String
pathOfBillingSoftware = """path"""
End Function
I am using the function above in my sql query :
SELECT *
FROM tableName IN pathOfBillingSoftware();
It is giving me the error: "error in from clause"
but when I am using it in vba code , it is working fine
a = pathOfBillingSoftware()
sql = "INSERT INTO tableName " & _
"IN " & a & _
" SELECT * FROM tableName"
currentdb.Execute sql
Any Solution ?
This is dynamic SQL. You seem to already have found the solution: use VBA code. You can only use functions to return values in static SQL.
If you want to return operators or other things that aren't standard values, you need to use dynamic SQL, and thus need to use VBA.
You can create queries through VBA if you want, but note that once they are created, they are static.
Sample code to create a query with your function
CurrentDb.CreateQueryDef "MyQuery", "SELECT * FROM tableName IN " & pathOfBillingSoftware();

Access 2007 VBA: Returning data from SQL statements that use multiple variables

I am working on a form that is meant to analyze financial data ahead of an insurance policy renewal. It needs to pull various premium and claim $$ totals from the tables, and insert them into the form. From there, it will run some calculations with them, but that should be the easy part. Where I'm struggling is the SQL statements to get the data, in the first place.
After narrowing it down a bit, I've found that the problem is the code is putting the SQL statement into the field on the form, instead of the answer the SQL statement should be providing. I have tried multiple things I've seen online, and can't figure out how to resolve this.
One of the SQL statements reads like this:
L12W = "SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit FROM tblActPrem " _
& " WHERE tblActPrem.EntID = '" & Me.ctlActEntID & "' " _
& " AND tblActPrem.PolNum = '" & Me.ctltblRnwlTrack_PolNum & "'" _
& " AND tblActPrem.APDate BETWEEN #" & L12M & "# AND #" & Me.ctlRnwAnalysisDt & "#;"""
It should be totalling premium data from the table, where the policy number and account number match what's on the form, and between the selected dates, and putting that total into the field on the form. Instead, I get this on the form:
SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit FROM tblActPrem WHERE tblActPrem.EntID = '1235' AND tblActPrem.PolNum = 'Policy1' AND tblActPrem.APDate BETWEEN #1/1/2014# AND #1/1/2015#;"
That is exactly how the statement should be running, but can anyone tell me how to make the leap from the statement, to the data?
Thank you!
Consider using DLookup or DSum in the control source of the form's field.
DLookup Solution
First, change your VBA SQL query into a stored SQL Query (notice quotes and # symbols are not necessary when referencing form controls):
SELECT Sum(tblActPrem.APWrit) AS SumOfAPWrit
FROM tblActPrem
WHERE tblActPrem.EntID = Forms!<yourformname>!ctlActEntID
AND tblActPrem.PolNum = Forms!<yourformname>!ctltblRnwlTrack_PolNum
AND tblActPrem.APDate BETWEEN Forms!<yourformname>!L12M
AND Forms!<yourformname>!ctlRnwAnalysisDt
And then in the form field textbox's control source use the DLookUp function (no criteria argument is needed since this should return only one value).
= DLookUp("SumOfAPWrit", "<yournewqueryname>")
DSum Solution
Alternatively, you can change the entire SQL statement into a DSum but notice how long the criteria (WHERE statement) would have to be.
= DSum("APWrit", "tblActPrem", "EntID = Forms!<yourformname>!ctlActEntID
AND PolNum = Forms!<yourformname>!ctltblRnwlTrack_PolNum
AND APDate BETWEEN Forms!<yourformname>!L12M AND Forms!<yourformname>!ctlRnwAnalysisDt")

VBScript not executing sql statment properly

I write you this time because a VBScript that one of the application my company uses to retrieve information from an Oracle database does not seem to be working properly. Here are the facts:
There's part of the code that does the following:
sSql = "SELECT REQ_PAYMODE" & _
" FROM SYSADM.GBPRESTATIEGROEP" & _
" WHERE 1=1" & _
" AND SLEUTEL = " & sKeyPrestatiegroep
Set oRSGBPrest = connADO.execute(sSql)
If Not oRSGBPrest.EOF Then
sRequestPaymodeKey = oRSGBPrest("REQ_PAYMODE")
Else
//error handling
End If
Using a Statement Tracer for Oracle (www.aboves.com) I can capture that same statement with its corresponding value:
SELECT REQ_PAYMODE FROM
SYSADM.GBPRESTATIEGROEP WHERE 1=1 AND
SLEUTEL = 1572499
Now, the VBScript is supposed to take that value and execute another query:
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & sRequestPaymodeKey
Set oRSPaymodes = connADO.execute(sSql)
Right in this last line of code, the script throws an error that says:
ORA-00936: missing expression at line XXX --> Set oRSPaymodes = connADO.execute(sSql) <--
Which basically means that the query in (3) is not correct, which also means that for some reason sRequestPaymodeKey is empty. I cannot tell this for sure because this failing sql statement does not appear in the statement tracer, but that's the only explanation I could find. However, the worst part is that when running the query (2) on SQLDeveloper (that's where value sRequestPaymodeKey comes from) it shows a row with a value other than null or zero.
I can't think of anything else that might be happening here, maybe it's just a server thing... no idea.
Any suggestions from you guys? Any way I can actually debug a VBE file?
Your help is much appreciated!
You need to cast sRequestPaymodeKey as a vbLong which corresponds to sql's INT. I'm assuming PAM_KEY is an INT. A recordset will return a string value. So, your code would look like this:
If IsNumeric(sRequestPaymodeKey) Then
sSql = "SELECT PAM_CODE" & _
" FROM SYSADM.PAYMODES" & _
" WHERE 1=1" & _
" AND PAM_KEY = " & CLng(sRequestPaymodeKey)
Set oRSPaymodes = connADO.execute(sSql)
Else
'do error handling due to bad returned data(empty string?)
End If
Also, consider parameterizing your queries to prevent sql injection.
A few ideas to try:
Before Set oRSPaymodes = connADO.execute(sSql), put in a MsbBox and see what SQL is being executed. Is it valid? Will it run in a Oracle query analyzer(if there is one)?
Hard code a valid value in place of sRequestPaymodeKey. Does it work then?