MS Access VBA Add Decimals to Output - sql

I have data which have 2 decimal places (See Figure) and am using the function to subtract the two values but I'm getting a rounded number as my output. I've tried to add float to the following expression "(L.M123_Corr_Integrator-R.M123_Corr_Integrator)" but it's throwing out an error. I'm not familiar with sql/vba code so any useful information would help.
sql = "UPDATE (SELECT R.DateLog , ( L.M123_Corr_Integrator - R.M123_Corr_Integrator) AS Gross " & _
"FROM tbl_M123_DataSet AS L INNER JOIN tbl_M123_DataSet AS R " & _
"ON L.DateLog = DATEADD('d', 1, R.DateLog)) as T " & _
"INNER JOIN tbl_M123_DataSet ON tbl_M123_DataSet.DateLog = T.DateLog " & _
"Set Gross_kWh = Gross"
dbs.Execute sql, dbFailOnError
MsgBox dbs.RecordsAffected & " rows affected on column GrossKW"
That query unobfuscated looks like this:
UPDATE
(
SELECT
R.DateLog,
L.M123_Corr_Integrator - R.M123_Corr_Integrator AS Gross
FROM
tbl_M123_DataSet AS L
INNER JOIN tbl_M123_DataSet AS R
ON L.DateLog = DATEADD('d', 1, R.DateLog)
) AS T
INNER JOIN tbl_M123_DataSet
ON tbl_M123_DataSet.DateLog = T.DateLog
SET Gross_kWh = Gross

It looks to me that you have the table field Gross_kWh set to integer. In the table design view, highlight the row Gross_kWh and set its number type to 'Double'.
Also be aware that Access will sometimes round numbers for display, but the decimal accurate number is stored in the table correctly.

Related

Only show field value if another field is equal to “X” VBA Acces

Let's say I've got this query containing multiple tables.
Containing this data when run :
I want the query to show me the data exactly as it is in the database but when I run my SQL statement it'll show it as if on the second row the field OpslagLocatie has the same data as the field above it.
Outcome :
My solution :
Me.[Keuzelijst EAN artikel op vooraad].RowSource =
"SELECT TussenMAATenARTKEL.EAN_Code AS [EAN Code], TbOpzoekKleur.Kleur AS Kleur, TbOpzoekVoorraadMaat.VoorraadMaten AS Maat, Sum(Stock.Aantal_per_Lokatie) AS Aantal, TbOpzoekVoorraadLocatie.VoorraadLocatie AS Lokatie, Stock.ArtikelDetail_ID AS Detail, IIf([TussenMAATenARTKEL].[Opslaglocatie], [Stock].[VoorraadLocatie_ID]=8,[TussenMAATenARTKEL].[OpslagLocatie]) AS [Opslag Locatie] " & _
"FROM (TbOpzoekVoorraadMaat RIGHT JOIN (TbOpzoekKleur RIGHT JOIN TussenMAATenARTKEL ON TbOpzoekKleur.ColorCode = TussenMAATenARTKEL.Colorcode) ON TbOpzoekVoorraadMaat.VoorraadNummer = TussenMAATenARTKEL.VoorraadNummer) RIGHT JOIN (TbOpzoekVoorraadLocatie RIGHT JOIN Stock ON TbOpzoekVoorraadLocatie.VoorraadLocatie_ID = Stock.VoorraadLocatie_ID) ON TussenMAATenARTKEL.ArtikelDetail_ID = Stock.ArtikelDetail_ID " & _
"GROUP BY TussenMAATenARTKEL.EAN_Code, TbOpzoekKleur.Kleur, TbOpzoekVoorraadMaat.VoorraadMaten, TbOpzoekVoorraadLocatie.VoorraadLocatie, Stock.ArtikelDetail_ID, Stock.VoorraadLocatie_ID, TussenMAATenARTKEL.Artikel_ID, TussenMAATenARTKEL.OpslagLocatie " & _
"HAVING (((Sum(Stock.Aantal_per_Lokatie)) <> 0) And ((TussenMAATenARTKEL.Artikel_ID) = " & test & ")) " & _
"ORDER BY TbOpzoekVoorraadMaat.VoorraadMaten;"
Outcome after updating my code with an iif statement :
After running my code the field TussenMAATenARTKEL.OpslagLocatie only shows the values -1 or 0. I expect it to show or not show the OpslagLocatie instead of -1 and 0.
What am I doing wrong?
That's because your OpslagLocatie is a lookup field.
So, in your query, join and include the table and the field in this from where OpslagLocatie looks up the code KBA-ACC.

MS Access VBA SQL SELECT * INTO tempTbl WHERE Stuff="" AND OtherStuff BETWEEN Date Range

I have a form with one text box, two combo boxes (dropdowns), and two text boxes with input masks for mm/dd/yyyy 99/99/0000;0;_
I am attempting to use all of these fields as filters for a subform.
I have the controls set to fire after update and run a sub that builds a SELECT * INTO sql string for a temp Table that is then sourceobject'ed back to the subform.
In code I have for each control I have code building a snippet of the Where statement for the final sql. the snippet grows as needed, is labeled "Filter"
Some other non-Finished Code....
If Not IsNull(txtDateFrom) Then
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= " & Me.txtDateFrom & ")" & " And " & "([Date_LastSaved] <= " & Me.txtDateTo & ")"
End If
Dim sql As String
sql = "SELECT * INTO tmpTable FROM tblReview"
If Not IsNull(Filter) Then
sql = sql & " WHERE " & Filter
End If
My issue and question is that I am testing this one specific situation where there will be Filter = Filter & " AND " & "DATE_STUFF"
where the final sql looks like...
SELECT * INTO tmpTable FROM tblReview WHERE ReviewStatus = 'Quoted' AND ([Date_LastSaved] >= 09/12/2018) And ([Date_LastSaved] <= 10/16/2018)
which should have some result with the test data. Yet, the tmpTable is empty.
This is only happening when I apply a date range criteria.
I tried BETWEEN but could not nail down the syntax.
Any insight is greatly appreciated, Thanks!
UPDATE:
Answer:
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= #" & Me.txtDateFrom & "#)" & " And " & "([Date_LastSaved] <= #" & Me.txtDateTo & "#)"
If you want to use dates then they must be quoted. If you just say 10/16/2018 then you are dividing the integer 10 by 16 by 2018 which will yield an integer zero. It will then convert the dates to an integer to do the compare, which will yield a much bigger number, and thus you get no rows.
Any date testing should always be done using date types rather than strings. I think in msaccess you can surround it in #, but not sure. Just research this.

SQL Server Join Tables By Combining 2 Columns

This sounds ridiculously easy but I've tried so many different approaches. This query is just set up weird and I'm trying to JOIN it but there's not a common column I can do that with. There is, however, a LastFirst column (consists of LastName then FirstName) written in the context of DOE, JOHN. Then on the columns I'm trying to join that with it's just FirstName (John) and LastName (Doe).
I'm actually trying to select data from 4 tables that all are returning 1 row. These 2 tables can be joined:
SELECT
RIFQuery.*,
_Employee.EmployeeLastName + ', ' + _Employee.EmployeeFirstName AS EmployeeLastFirst,
_Employee.EmployeeTitle, _Employee.Phone As EmployeePhone,
_Employee.EmailAddress As EmployeeEmailAddress
FROM
RIFQuery
INNER JOIN
_Employee ON RIFQuery.CreatedBy = _Employee.AutoNumber
WHERE
RIFQuery.Autonumber = 1
This one has nothing to join with so I'll probably union it and null remaining columns:
SELECT *
FROM tblOrganization
This is the table that contains LastName and FirstName that I'm trying to join with RIFQuery.LastFirst:
SELECT
Gender As ClientGender, DOB As ClientDOB, SSN As ClientSSN
FROM
_Clients
WHERE
_Clients.LASTNAME = left(RIFQuery.LastFirst, len(RIFQuery.LastFirst)-CHARINDEX(',', REVERSE(RIFQuery.LastFirst)))
AND _Clients.FIRSTNAME = ltrim(substring(RIFQuery.LastFirst, len(RIFQuery.LastFirst)-CHARINDEX(',', REVERSE(RIFQuery.LastFirst))+2, len(RIFQuery.LastFirst)))
In that WHERE statement the code will split the LastFirst column and get the row by searching their LastName and FirstName. I'm wondering if there's a way I can write that into a JOIN? Otherwise I can probably UNION and null remaining columns but it will look very ugly.
UPDATE
I tried 2 suggestions from here and both result in a syntax error. I forgot to mention that I'm executing this code inside Microsoft Access VBA and trying to retrieve a DAO.RecordSet. I had to remove some table names in the SELECT statement to get past a syntax error from there, so maybe I should update the question to reflect MS ACCESS and not SQL Server, although only the query is the only pure Access object and the rest are linked ODBC tables to SQL Server.
UPDATE
Just one of those issues where I can't sleep until it's fixed and will obsess until it is. If I take out all _Employee references (from SELECT and JOIN statements), it wants to work but errors about too few parameters. I just now know this is related to _Employee. Getting different results from applying parentheses and just hoping I'll get lucky and hit on it.
The error is caused by this line:
INNER JOIN [_Employee] ON [_Employee].[AutoNumber] = [RIFQuery].[CreatedBy]
I get this error:
"Syntax error (missing operator) in query expression".
As seen in this screenshot:
Here's my latest query I'm playing with, minus the parentheses:
str = "SELECT [RIFQuery].*, " & vbCrLf & _
" ([_Employee].[EmployeeLastName] & ', ' & [_Employee].[EmployeeFirstName]) AS [EmployeeLastFirst], " & vbCrLf & _
" [_Employee].[EmployeeTitle], " & vbCrLf & _
" [_Employee].[Phone] AS [EmployeePhone], " & vbCrLf & _
" [_Employee].[EmailAddress] AS [EmployeeEmailAddress], " & vbCrLf & _
" [_Clients].[Gender] AS [ClientGender], " & vbCrLf & _
" [_Clients].[DOB] AS [ClientDOB], " & vbCrLf & _
" [_Clients].[SSN] AS [ClientSSN] " & vbCrLf & _
"FROM [_Clients] " & vbCrLf & _
" INNER JOIN [RIFQuery] ON [RIFQuery].[LastFirst] = [_Clients].[LASTNAME] & ', ' & [_Clients].[FIRSTNAME] " & vbCrLf & _
" INNER JOIN [_Employee] ON [_Employee].[AutoNumber] = [RIFQuery].[CreatedBy] " & vbCrLf & _
"WHERE [RIFQuery].[Autonumber] = 1;"
For debugging purposes, if I remove those last 2 lines and the _Employee SELECT statements, it'll process the query without a problem. If anyone has any ideas just let me know.
I was focused on that RIFQuery JOIN statement being the culprit for the longest time but I've found that simply is not the issue any more. With that said, this thread has been essentially solved and I appreciate the help.
MS Access is using a slightly different syntax than SQL Server when it comes to using more than one JOIN. You could leave out the JOIN with the _Clients (making it a cross join) and move that condition to the WHERE clause, which would make the query look like this (and which would allow you to display the design window for the query without any problem)
SELECT RIFQuery.*,
EmployeeLastName + ', ' + EmployeeFirstName As EmployeeLastFirst,
EmployeeTitle, Phone As EmployeePhone, EmailAddress As EmployeeEmailAddress,
Gender As ClientGender, DOB As ClientDOB, SSN As ClientSSN
FROM _Clients, RIFQuery INNER JOIN _Employee ON RIFQuery.CreatedBy = _Employee.AutoNumber
WHERE RIFQuery.LastFirst = _Clients.LASTNAME & ", " & _Clients.FIRSTNAME;
Instead of assembling the query string in VBA just for being able to change the parameter value, I suggest to save the following query as an Access object (maybe qryRIF):
PARAMETERS lgRIF Long;
SELECT RIFQuery.*,
EmployeeLastName + ', ' + EmployeeFirstName As EmployeeLastFirst,
EmployeeTitle, Phone As EmployeePhone, EmailAddress As EmployeeEmailAddress,
Gender As ClientGender, DOB As ClientDOB, SSN As ClientSSN
FROM _Clients, RIFQuery INNER JOIN _Employee ON RIFQuery.CreatedBy = _Employee.AutoNumber
WHERE RIFQuery.LastFirst = _Clients.LASTNAME & ", " & _Clients.FIRSTNAME
AND RIFQuery.Autonumber = [lgRIF];
In your VBA code, you can use code like the following to grab the QueryDef object, assign the parameter value and open a recordset:
With CurrentDb.QueryDefs!qryRIF
!lgRIF = lgRIF
With .OpenRecordset()
' ... your code ...
.Close
End With
.Close
End With

VBA Insert Query: "Query input must contain at least one table or query""

I am importing data from an Excel spreadsheet into tblPOLinesTemp table, and then I have to apppend those to tblPOLines table. I am trying to execute an insert into SQL statement from VBA, but keep getting "Query input must contain at least one table or query" as error, and I cannot seem to figure out what is wrong as the SQL statement works when running it in Access! It is driving me crazy! Can you help?
My code (I have Dim'ed AppendPOlines as String):
AppendPOLines = "INSERT INTO tblPOlines ( PurchaseOrderID, PurchaseOrderLineID, [Material#], FirstDeliveryDate, Quantity, CreatedBy )" _
& "SELECT tblPOLinesTemp.PurchaseOrderID, tblPOLinesTemp.PurchaseOrderLineID, tblPOLinesTemp.[Material#], tblPOLinesTemp.FirstDeliveryDate, tblPOLinesTemp.Quantity, [TempVars]![VarUserID] AS CreatedBy" _
& "FROM tblPOLinesTemp LEFT JOIN tblPOlines ON (tblPOLinesTemp.PurchaseOrderLineID = tblPOlines.PurchaseOrderLineID) AND (tblPOLinesTemp.[PurchaseOrderID] = tblPOlines.[PurchaseOrderID])" _
& "WHERE (((tblPOlines.PurchaseOrderLineID) Is Null) AND ((tblPOlines.PurchaseOrderID) Is Null));"
CurrentDb.Execute AppendPOLines, dbFailOnError
Note that the Left Joins is to ensure that the Query does not insert rows with similar Purchase Order and Purchase Order Line ID - to avoid duplicate rows.
Thank you!
After and before each ["] put a blank space :
AppendPOLines = " INSERT INTO tblPOlines( PurchaseOrderID, PurchaseOrderLineID, [Material#], FirstDeliveryDate, Quantity, CreatedBy ) " _
& " SELECT tblPOLinesTemp.PurchaseOrderID, tblPOLinesTemp.PurchaseOrderLineID, tblPOLinesTemp.[Material#], tblPOLinesTemp.FirstDeliveryDate, tblPOLinesTemp.Quantity, [TempVars]![VarUserID] AS CreatedBy " _
& " FROM tblPOLinesTemp LEFT JOIN tblPOlines ON (tblPOLinesTemp.PurchaseOrderLineID = tblPOlines.PurchaseOrderLineID) AND (tblPOLinesTemp.[PurchaseOrderID] = tblPOlines.[PurchaseOrderID]) " _
& " WHERE (((tblPOlines.PurchaseOrderLineID) Is Null) AND ((tblPOlines.PurchaseOrderID) Is Null)); "
your query is executed like following:
INSERT INTO tblPOlines( PurchaseOrderID, PurchaseOrderLineID, [Material#], FirstDeliveryDate, Quantity, CreatedBy )SELECT tblPOLinesTemp.PurchaseOrderID, tblPOLinesTemp.PurchaseOrderLineID, tblPOLinesTemp.[Material#], tblPOLinesTemp.FirstDeliveryDate, tblPOLinesTemp.Quantity, [TempVars]![VarUserID] AS CreatedByFROM tblPOLinesTemp LEFT JOIN tblPOlines ON (tblPOLinesTemp.PurchaseOrderLineID = tblPOlines.PurchaseOrderLineID) AND (tblPOLinesTemp.[PurchaseOrderID] = tblPOlines.[PurchaseOrderID])WHERE (((tblPOlines.PurchaseOrderLineID) Is Null) AND ((tblPOlines.PurchaseOrderID) Is Null));
so CreatedByFrom is wrong and you get this error:
"query input must contain at least one table or query"

N Top Record Selection Based on Own SQL Statement in MS-Access

I'm re-writing a small ms-access application to take examinations on.
What they want is for the tests to grab a set of random questions based on how large the exam's size is.
If each exam was a set number of questions, I could just stick the number in the TOP statement and be done with it, but there are a variable number of questions for each exam, so I want to replace the constant number next to the TOP with a field from the query.
What I basically want is like this:
SELECT TOP tblExam.[ExamSize] *
FROM tblExamQuestions INNER JOIN tblExam
ON tblExamQuestions.ExamID = tblExam.ExamID
WHERE tblExam.ExamID = 10
ORDER BY Rnd(tblExamQuestions.ExamQuestionID);
I'm supplying the new ExamID to this query for each exam session when I open the report, so this will probably get in the way.
DoCmd.OpenForm strExamName, , , "tblExam.ExamID = " & strExamID
I think you would have to build the query dynamically.
sSQL="SELECT TOP " & DlookUp("ExamSize","tblExam","ExamID = 10") _
& " FROM tblExamQuestions INNER JOIN tblExam " _
& "ON tblExamQuestions.ExamID = tblExam.ExamID " _
& "WHERE tblExam.ExamID = 10 " _
& "ORDER BY Rnd(tblExamQuestions.ExamQuestionID)"
'' Permanently change an existing query
CurrentDB.QueryDefs("MyReportQuery").SQL=sSQL