Running a parameter query in Access VBA - sql

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.

Related

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

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.

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

Running SQL Query In Access VBA

Im trying to run an SQL query in Access VBA but my query is too long to fit in one line
INSERT INTO tblProduct SELECT[SAMPartGrp],[ProductPrefix] ,[ProductCode] ,[pcode1],[pcode2],[SubPart1],[SubPart2],[ProductCodeNew],[ProductDescription],[MadeFrom],[MadeFromDescription],[Field1],[SamFamilySort1],[SamFamilySort2],[SamFamilySort3]
,[SamFamilySort4],[SamFamilySort5],[Grade],[Length],[Thickness],[fWidth],[Factor],[CubicMtrs],[CubicMtrsFull],[Weight(T)],[DrawingFilepath],[PackingFilePath],[EFACSProductGrouping],[BatchSize],[PackSize],[Density],[createdby],[createddate],[ProductType],[reorderpolicy],[EFACSExport],[PreactorExport],[customer],[Obsolete/DoNotUse],[noinminipack],[piecesincrate],[minipackheight],[DimA],[DimB],[DimC],[DimD],[DimE],[DimF],[DimG],[DimH],[DimI],[DimJ],[DimK],[DimL],[DimM],[DimN],[DimO] ,[DimP],[DimQ],[DimR],[DimS],[DimT],[DimU],[DimV],[DimW],[DimX],[DimY],[DimZ],[TolA],[TolB],[TolC],[TolD],[TolE],[TolF],[TolG],[TolH],[TolI],[TolJ],[TolK],[TolL],[TolM],[TolN],[TolO],[TolP],[TolQ],[TolR],[TolS],[TolT],[TolU],[TolV],[TolW],[TolX],[TolY],[TolZ]
,[Dimension],[Main],[Saws],[Moulders],[PaintLines],[XCut],[DET],[MitreSaw],[Wrapper],[Blocks]
,[HingeRecess],[ShrinkWrap],[CNC],[SW],[ShrinkWrapPackSize] ,[SAMBarCode],[machinedaway],[ExcludeFromPreactorUpload],[UseOtherM3XC],[UseOtherM3XC81],[UseOtherM3MS],[UseOtherM3MS83],[comment],[samtype1],[fsc],[LabelPack],[LabelPiece],[trml],[vtype1],[vtype2],[minipack] ,[profile],[madefromlength],[productchamp],[packtype],[uom],[acumatica],[Cupboard],[AcmtaExport],[ExportedtoAcmta],[PostingClass]
FROM tblProducts
so it wont run the full query at once, is there a workaround for this?
You have several issues.
One is that SQL server and Access SQL are not the same. Access SQL is a lot more limited, so just because an SQL query runs on the SQL server does not mean it will run in Access. To run SQL Server queries that are not Access SQL compatible you have to use a pass-through query.
The other issue is that Access table names and SQL server table names are no necessarily the same.
Now, assuming you have taken all that into account and your query is actually Access SQL compatible, you can run it like this:
Dim sql as String
sql = "Query part A"
sql = sql & "Query Part B"
... repeat as necessary
DoCmd.RunSQL sql
SQL doesn't take white space into account, this should run the entire query at once.
I think your problem is that you want to use SELECT INTO with TSQL
See here for more information:
https://msdn.microsoft.com/en-us/library/bb208934(v=office.12).aspx
Are you just talking about wraparound formatting, where you use the "& _" to continue your string?
strSQL = "SELECT [SAMPartGrp],[ProductPrefix] ,[ProductCode] ,[pcode1], " & _
"[pcode2], [SubPart1],[SubPart2],[ProductCodeNew],[ProductDescription], " & _
"[MadeFrom], [MadeFromDescription],[Field1],[SamFamilySort1], " & _
"[SamFamilySort2],[SamFamilySort3],[SamFamilySort4], " & _
"[SamFamilySort5], [Grade], "
Try this.
Dim strSQL as String
strSQL = "INSERT INTO tblProduct SELECT[SAMPartGrp],[ProductPrefix] , " & _
"[ProductCode] ,[pcode1],[pcode2],[SubPart1],[SubPart2],[ProductCodeNew], " & _
"[ProductDescription],[MadeFrom],[MadeFromDescription],[Field1], " & _
"[SamFamilySort1],[SamFamilySort2],[SamFamilySort3], [SamFamilySort4], " _
"[SamFamilySort5],[Grade],[Length],[Thickness], [fWidth],[Factor], " & _
"[CubicMtrs],[CubicMtrsFull],[Weight(T)],[DrawingFilepath], " & _
"[PackingFilePath],[EFACSProductGrouping],[BatchSize], " & _
"[PackSize],[Density],[createdby],[createddate],[ProductType], " & _
"[reorderpolicy],[EFACSExport],[PreactorExport],[customer], " & _
"[Obsolete/DoNotUse],[noinminipack],[piecesincrate], [minipackheight], " & _
"[DimA],[DimB],[DimC],[DimD],[DimE],[DimF],[DimG],[DimH], " & _
"[DimI],[DimJ],[DimK],[DimL],[DimM],[DimN],[DimO] ,[DimP], " &_
"[DimQ],[DimR],[DimS],[DimT],[DimU],[DimV],[DimW],[DimX], " & _
"[DimY],[DimZ],[TolA],[TolB],[TolC],[TolD],[TolE],[TolF], " & _
"[TolG],[TolH],[TolI],[TolJ],[TolK],[TolL],[TolM],[TolN], " & _
"[TolO],[TolP],[TolQ],[TolR],[TolS],[TolT],[TolU],[TolV], " & _
"[TolW],[TolX],[TolY],[TolZ],[Dimension],[Main],[Saws], " &_
"[Moulders],[PaintLines],[XCut],[DET],[MitreSaw],[Wrapper], " &_
"[Blocks],[HingeRecess],[ShrinkWrap],[CNC],[SW], " & _
"[ShrinkWrapPackSize] ,[SAMBarCode],[machinedaway], " & _
"[ExcludeFromPreactorUpload],[UseOtherM3XC],[UseOtherM3XC81], " & _
"[UseOtherM3MS],[UseOtherM3MS83],[comment],[samtype1],[fsc], " & _
"[LabelPack],[LabelPiece],[trml],[vtype1],[vtype2],[minipack] , " & _
"[profile],[madefromlength],[productchamp],[packtype],[uom], " & _
"[acumatica],[Cupboard],[AcmtaExport],[ExportedtoAcmta], " & _
"[PostingClass] FROM tblProducts;"
DoCmd.RunSQL strSQL

How can I do a simple join on a subquery?

I've been at this for 2 hours and have no idea what the issue is. Although I have worked a fair amount with SQL, I'm struggling with the idiosyncrasies in Access queries relative to SQL queries when using the ADO ACE connection to query Excel worksheets. My goal at it's most basic is to do a join with a subquery. I have simplified the query considerably to display the issue, so please excuse the fact that it wouldn't really make sense to run a query like this.
The error I keep getting is Syntax Error in From Clause. The worksheet only has 2 columns, Account Number and Cost
Sub stackoverflow()
Dim acctcon As New ADODB.Connection
Dim acctrec As New ADODB.Recordset
acctcon.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Documents\Book1.xlsx;" & _
"Extended Properties=" & Chr(34) & "Excel 12.0 Xml;HDR=YES" & Chr(34) & ";"
acctcon.Open
querystr = "Select [Accounts$].[Account Number], [mm].[Cost] " & _
"FROM [Accounts$] " & _
"JOIN (Select [Account Number], [Cost] " & _
"FROM [Accounts$]) As mm " & _
"ON [Accounts$].[Account Number] = [mm].[Account Number]"
acctrec.Open querystr, acctcon
'Syntax Error on From Clause
End Sub
Try to reset the Close bracket behind As mm
querystr = "Select [Accounts$].[Account Number], [mm].[Cost] " & _
"FROM [Accounts$] " & _
"INNER JOIN (Select [Account Number], [Cost] " & _
"FROM [Accounts$] As mm) " & _
"ON [Accounts$].[Account Number] = [mm].[Account Number]"
But you have to replace the inner join, because it makes no sense like #krish KM stated. I suppose you took it as a placeholder.

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.