ms-access run-time error 3075 extra ) in vbasql - sql

Code
strSQL = "SELECT tblHS_area_fields.hsaf_id " _
& "FROM tblHS_area_fields " _
& "WHERE (((tblHS_area_fields.hs_area_id)=" & hs_area_id & ") AND ((tblHS_area_fields.hsf_id)=13))"
Set rs = db.OpenRecordset(strSQL)
Errors
The error when trying to run from a Form is:
Extra ) in query expression '(((tblHS_area_fields.hs_area_id)=" &
> hs_area_id & ") AND ((tblHS_area_fields.hsf_id)=13))'
Getting an error from immediate window:
Compile error: expected: line number or label or statement or end of statement
All fields are numbers.
What is wrong with the VBA code and SQL statement?

Just remove all brackets in your sql:
strSQL = "SELECT tblHS_area_fields.hsaf_id " & _
"FROM tblHS_area_fields " & _
"WHERE tblHS_area_fields.hs_area_id = " & hs_area_id & " AND tblHS_area_fields.hsf_id = 13 "
In this case you don't need the brackets.

Not an answer, but too long for a comment:
Next time, add a Debug.Print strSql, then create a query in SQL view, copy you SQL statement from the debug window (ctrl+G) and paste you statement there.
Or just paste it in Visual Studio...
You should then quickly see the issue(s)

Consider to debug-print and log your SQL before executing: Debug.print(strSQL).
Opening brackets must match closing ones
Some break-down helps recognizing and matching, correct is:
strSQL = "SELECT hsaf_id" _
& " FROM tblHS_area_fields" _
& " WHERE (" _
& "( hs_area_id =" & hs_area_id & ")" _
& " AND ( hsf_id = 13 )" _
& ")"
For SQL templates you could also use string replace function or string-templating with a custom-function. See VBA string interpolation syntax.

Related

Use Dlookup inside SQL in VBA for Microsoft Access causes Unknown Error

I am trying to update a field based on a lookup field in VBA. This is the code that I have:
SQL = "UPDATE tblDispatch td " & _
"SET td.NumOfStops = Dlookup(""NumOfStops"", ""qryStops"", ""PK = td.PK"")" & _
"WHERE td.DispatchDate = #" & Me.tbDate.Value & "#;"
DoCmd.RunSQL SQL
The syntax and everything looks correct but it keeps giving me a weird error. "Run-time error '2741' Unknown" What is this error and how can I fix it?
Just a guess based on the limited information available, but try:
SQL = "UPDATE tblDispatch td " & _
"SET td.NumOfStops = Dlookup(""NumOfStops"", ""qryStops"", ""PK = '"" & td.PK & ""'"") " & _
"WHERE td.DispatchDate = #" & Me.tbDate.Value & "#;"
DoCmd.RunSQL SQL
Or if PK isn't a string, then:
SQL = "UPDATE tblDispatch td " & _
"SET td.NumOfStops = Dlookup(""NumOfStops"", ""qryStops"", ""PK = "" & td.PK) " & _
"WHERE td.DispatchDate = #" & Me.tbDate.Value & "#;"
DoCmd.RunSQL SQL

MS-Access VBA select query with multiple criteria

I have a dropdown box in an MS Access form which is populated by the following select query:
strSQL = "SELECT [Process] " _
& "FROM [dbo_tbl_Area_Process] " _
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & ";"
Me.Process.RowSource = strSQL
I would like to add Active = -1 as a second criteria to the query to further limit the selections.
I have tried, so far unsuccessfully to add this second criteria and am at a loss as to how to proceed. Any help from the community would be most appreciated.
I have tried the following where conditions:
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " and Active =-1"
This does not return any results.
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " and Active ="-1""
This has a compile error:
Expected:end of statement
Following on from mintys comment regarding linked SQL server tables I changed the query to the following:
strSQL = "SELECT dbo_Tbl_Area_Process.Process " _
& "FROM dbo_Tbl_Area_Process " _
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " AND Active=True"
Adding the table references to the SELECT and FROM lines gives me the outputs I expected.
Thanks all for your comments

MS Access SQL Too Few Parameters: Expected 2

In MS Access 2010, I have the following query which randomly orders the data and puts it in a new sheet. Before I added in the WHERE, it was working, but now I get an error telling me:
Too few parameters: Expected 2.
Does anybody know how I could fix this?
sqlQuery = "SELECT [My_Sheet].* " & _
" INTO My_New_Sheet" & _
" FROM [My_Sheet] " & _
" WHERE [Some_Field] = [Some_Possible_Value_For_The_Field] " & _
" ORDER BY Rnd(-(100000*[Some_Other_Field])*Time())"
Debug.Print sqlQuery
CurrentDb.Execute sqlQuery
Where [Some_Possible_Value_For_The_Field] is comes from [My_Sheet]
Note that this is Access SQL
sqlQuery = "SELECT [My_Sheet].* " & _
" INTO My_New_Sheet" & _
" FROM [My_Sheet] " & _
" WHERE [Some_Field] = '" & [Some_Possible_Value_For_The_Field] & "'" & _
" ORDER BY Rnd(-(100000*" & [Some_Other_Field] & ")*Time())"
Debug.Print sqlQuery
CurrentDb.Execute sqlQuery
When you use a form variable, the value has to be read from outside of the SQL statement. Hence why we close the statement with double quote, add the field value, and then continue by opening the with a double quotes again.
Notice that you need to keep the field qualifiers. In this case I assumed your first field was a string which requires the single quote qualifiers and the second variable as an integer which doesn't require qualifiers.

Running a parameter query in Access VBA

I am trying to run the following query in a VBA function. I keep getting "Too few parameters. Expected 1."
strSQL = "Parameters [Report Date] DateTime;" & vbCrLf & _
"SELECT SCF.code AS [Stock Code], " & vbCrLf & _
"SCF.desc AS [Description], " & vbCrLf & _
"SCF.grp AS [Product Group]," & vbCrLf & _
"SCF.qCurr AS [Closing Stock], " & vbCrLf & _
"SCF.abp AS [Avg Price], " & vbCrLf & _
"Sum(([Closing Stock]*[Avg Price])) AS [STOCK VALUE], " & vbCrLf & _
"MaxDate.tDate AS [Last Transaction Date], " & vbCrLf & _
"Sum(IIf(([Last Transaction Date]>[Report Date]),([Closing Stock]*[Avg Price]),0)) AS [After Report Date], " & vbCrLf & _
"DateDiff(""d"",[Last Transaction Date],[Report Date]) AS [Days since Last Transaction], " & vbCrLf & _
"[Report Date]" & vbCrLf & _
"INTO [FinReport] " & vbCrLf & _
"FROM SCF RIGHT JOIN MaxDate ON MaxDate.parent = SCF.this "
strSQL = strSQL & _
"WHERE (SCF.qCurr <> 0) " & vbCrLf & _
"GROUP BY SCF.code, " & vbCrLf & _
"SCF.desc, " & vbCrLf & _
"SCF.grp, " & vbCrLf & _
"SCF.qCurr, " & vbCrLf & _
"SCF.abp, " & vbCrLf & _
"MaxDate.tDate" & vbCrLf & _
"ORDER BY MaxDate.tDate;"
Set qdf = db.CreateQueryDef("", strSQL)
qdf.Parameters("[Report Date]").Value = Form_IO_Form.ReportDate_TB.Value
qdf.Execute
I have verified that all fields (other than [Report Date] of course) exist and the query runs by itself as an access query (pop up asks for [Report Date]).
Help!
Edit 1:
As requested here is the DB file as a ZIP. It is an Access 2007 .accdb file
DB File
Your SQL statement will trigger error #3122 from the db engine:
You tried to execute a query that does not include the specified expression 'DateDiff("d",[Last Transaction Date],[Report Date])' as part of an aggregate function.
That error will cause the statement to fail before the db engine even considers any parameters.
When you build a SQL statement with VBA, it's better to start with one the db engine will accept. Then you should also follow the sound advice from #mwolfe02 to Debug.Print strSQL ... to give yourself an opportunity to examine the completed statement you're asking the db engine to execute.
Edit: Having examined the ACCDB file you uploaded, I still don't understand why your query doesn't trigger error #3122. However the query does work as a saved query and can work when you execute it from VBA code. The reason you got the complaint about "too few parameters" is that you weren't actually executing the temporary QueryDef you created. Instead you were attempting to execute the SQL text like this:
' Execute created Query '
CurrentDb.Execute strSQL, dbFailOnError
If you change to this approach (as you indicated in your question), it works without error:
qdf.Execute
I am guessing that you have a typo in one of your field names. The easiest way to find it is to throw a Debug.Print strSQL line immediately before your Set qdf... line.
Then create a new query in the Access UI, switch to SQL view, paste in the SQL text from the immediate window, and execute the query. Access will prompt you for the Report Date (which you are expecting) and the mistyped name of one of your fields.

Why do brackets in SQL around field name not work in Access VBA ADO?

In MS Access QBE if I paste the following SQL, it works correctly and I get 2 records back-
SELECT [tmp_binning].[bn_faibash] FROM [tmp_binning] WHERE key2='0210043-HOU-STOR' ORDER BY [tmp_binning].[bn_faibash];
But if I programmatically run the same query in VBA from an ADO object I get (incorrectly) no records. If I change the SQL to remove brackets around the field name, it does correctly return the 2 records in VBA ADO.
SELECT [tmp_binning].bn_faibash FROM [tmp_binning] WHERE key2='0210043-HOU-STOR' ORDER BY [tmp_binning].bn_faibash;
I've been unsuccessful googling to figure why this happens on my own, can anyone tell me why?
Thanks.
First, the brackets aren't required, either in the in Access UI or via ADO. Simply omit them in all environments and the problem should go away. (If it is the Access QBE thing that is adding the brackets then consider another tool or hand crafting your SQL code!)
Second, even with the brackets I can't reproduce the error using your SQL code e.g.
Sub gjskdjs()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE tmp_binning" & vbCr & "(" & vbCr & " bn_faibash VARCHAR(255)," & _
" " & vbCr & " key2 VARCHAR(255)" & vbCr & ");"
.Execute Sql
Sql = _
"INSERT INTO tmp_binning (bn_faibash, key2)" & _
" VALUES ('002', '0210043-HOU-STOR');"
.Execute Sql
Sql = _
"INSERT INTO tmp_binning (bn_faibash, key2)" & _
" VALUES ('001', '0210043-HOU-STOR');"
.Execute Sql
Sql = _
"SELECT [tmp_binning].bn_faibash " & vbCr & " FROM" & _
" [tmp_binning] " & vbCr & " WHERE key2 = '0210043-HOU-STOR'" & _
" " & vbCr & " ORDER " & vbCr & " BY [tmp_binning].bn_faibash;"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString
End With
Set .ActiveConnection = Nothing
End With
End Sub
Consider posting your schema as SQL DDL with sample data.