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
Related
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.
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
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
The block of code immediately following (given to me by a stackoverflow solver) works perfectly in MS-Access. I'm trying to convert it to work in a vb.net form accessing the very same MS-Access database. I get an error and cannot see my mistake. Are there any vb.net coders that can see what I'm doing wrong. The first block of code works in MS-Access and is the code I'm trying to convert. And the second block of code is my conversion attempt.
SELECT at.animalID, amt.milestoneType
FROM
animals_Table at
LEFT JOIN
(
SELECT animalID, milestoneType
FROM animalMilestones_Table
WHERE milestoneType = 'Intake'
) amt
ON at.animalID = amt.animalID
Now, my conversion attempt:
dim selectAnimal as string
selectAnimal = "SELECT at.animalID, amt.milestoneType" & _
" FROM animals_Table at" & _
" LEFT JOIN" & _
" (" & _
" SELECT animalID, milestoneType" & _
" FROM animalMilestones_Table" & _
" WHERE milestoneType = '" & "Intake" & "'" & _
" ) amt" & _
" ON at.animalID = amt.animalID"
The error code I get is
!ErrorInfo.GetDescription failed with E_FAIL(0x80004005)
It appears that ACE.OLEDB doesn't like at as a table alias. Try this instead
Dim selectAnimal As String
selectAnimal = "SELECT atbl.animalID, amtbl.milestoneType" & _
" FROM animals_Table atbl" & _
" LEFT JOIN" & _
" (" & _
" SELECT animalID, milestoneType" & _
" FROM animalMilestones_Table" & _
" WHERE milestoneType = '" & "Intake" & "'" & _
" ) AS amtbl" & _
" ON atbl.animalID = amtbl.animalID"
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.