Syntax error in Microsoft Access SQL Select query in VBA procedure - sql

I am having following VBA Code that has been giving a syntax error. Can someone please help me figure out what is causing the error?
Private Sub Command11_Click()
Dim EndingDate As Date
'Getting ending date from Label named endDate
EndingDate = endDate
StartingDateTxt = DateSerial(Year(EndingDate), Month(EndingDate) - 15, Day(EndingDate))
Dim customerRecords As New ADODB.Recordset
customerRecords.Open "SELECT COUNT(*) AS N FROM (SELECT DISTINCT E.Date,"&_
"E.[Inv Num], E.CusName, E.[Name Street1], E.[Name Street2], "&_
"E.[Name City], E.[Name State], E.[Name Zip], E.[Account #], E.Amount FROM TempFromExcel "&_
"AS E INNER JOIN TempFromExcel AS X ON E.CusName = X.CusName "&_
"WHERE (((DateDiff("d",X.Date,E.Date))>=30)) AND E.Date >= '" & StartingDateTxt & "' and"&_
"E.Date <= '" & endDate & "') AS T ;", _
CodeProject.Connection , _
adOpenStatic, _
adLockOptimistic, _
adCmdText
MsgBox customerRecords("N")
End Sub
My Query is taking both dates and finding the results that are between the two dates.
I think I may be missing at that part only. The rest seems fine as I had explicitly check the query and it runs fine. So is this right ?
E.Date >= '" & StartingDateTxt & "' and E.Date <= '" & endDate & "'
This has been corrected, in the answer but still am getting syntax error in Select statement first line. Am missing something?

In Microsoft Access SQL query you have to encapsulate Date value into ##, like for example, #06/01/2015#. Pertinent to your case it should look like:
E.Date >= #" & StartingDateTxt & "# AND E.Date <=#" & endDate & "#"
Hope this may help.

Try changing these lines:
"WHERE (DateDiff('d', X.Date, E.Date) >= 30 AND E.Date >= #" & Format(StartingDateTxt, "yyyy\/mm\/dd") & "# and " & _
"E.Date <= #" & Format(endDate, "yyyy\/mm\/dd") & "#) AS T ;", _

Related

MS-Access date comparison Datatype conflict

In my Project I have Orders which contain an amount of Hours which have to be invoiced by a Rate, both of them are stored in tables. The Orders have a ValidFrom date. All Orders have to be invoiced by the last Rate where the ValidFrom is before the Order.TimeStamp.
The solution that I've tried is:
OrderDate = DLookup("TimeStamp", "Order", "OrderID=" & ThisOrderID & ")
LastRateDate = DMAX ("ValidFrom", "CompanyRate", "CompanyID=" & ThisCompanyID & " AND ValidFrom <=" & OrderDate)
CompanyRate = DLookup ("Rate","CompanyRate", "CompanyID=" & ThisCompanyID & " AND "ValidFrom =" & LastRateDate)
This gives several different errors:
without semicolons (as written): Syntax error missing Operator.
with single semicolon ' Datatype Conflict
with double semicolon " (chr(34)) Datatype Conflict
I use a german Computer, with german as Windows and MS-Access language. I run the MS-Access 2013
How should I solve this?
Try this using the proper syntax:
OrderDate = DLookup("TimeStamp", "Order", "OrderID = " & ThisOrderID & "")
LastRateDate = DMax("ValidFrom", "CompanyRate", "CompanyID = " & ThisCompanyID & " AND ValidFrom <= #" & Format(OrderDate, "yyyy\/mm\/dd") & "#")
CompanyRate = DLookup("Rate", "CompanyRate", "CompanyID = " & ThisCompanyID & " AND ValidFrom = #" & Format(LastRateDate, "yyyy\/mm\/dd") & "#")

Showing totals from previous months, What am I missing?

when I run this code it isn't showing the right records I need to see. I'm missing something somewhere but I'm not seeing it. The idea is for this to pull a count of all completed, in progress and Not started from the previous month and give me the totals.
Sub Update()
StatusCount "Completed"
StatusCount "In Progress"
StatusCount "Not Started"
'StatusCount "Moved to Cleanup"
'StatusCount "N/A"
'StatusCount "This is a new category" ', Now - 2, Now + 3
End Sub
Sub StatusCount(ByVal status As String, Optional start_date As Date, Optional end_date As Date)
Dim i As Variant
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim qd As DAO.QueryDef
Set db = CurrentDb
Dim SQL As String
If start_date = 0 Or end_date = 0 Then
SQL = "insert into statussummary (Count,mmyy,status) Select count(*), [created], [research status] " & _
"from [gwc master list]" & _
"where [research status] = '" & status & "'" & _
"group by [research status], [created]"
Else
SQL = "insert into statussummary (Count,mmyy,status) Select count(*), [created],[research status] " & _
"from [gwc master list]" & _
"where [research status] = '" & status & "'" & _
" and [created] > #" & start_date & "# and created < #" & end_date & "#" & _
"group by [research status], [created]"
End If
db.Execute (SQL)
rc = db.RecordsAffected
If rc = 0 Then
Debug.Print status & ": " & rc
SQL = "insert into statussummary (Count,status) values (" & rc & ", '" & status & "')"
db.Execute (SQL)
End If
End Sub
Any help is appreciated
-D
First, you need to change your database table field names. As mentioned, "status" is reserved, as is "count". Therefore, your three fields should be something like [R_COUNT], [CREATED], [R_STATUS]. Then, you restructure your VBA code like so:
Sub StatusCount(ByVal status_var As String, Optional start_date As Date, Optional end_date As Date)
This should solve the first conflict with "status". Then, you modify your first SQL statement to specify the correct fields you are inserting into statussummary (as I changed the names to above). Don't forget that you missed a space or two in the code before the continuation marks.
If start_date = 0 Or end_date = 0 Then
SQL = "insert into statussummary ([R_COUNT], [CREATED], [R_STATUS]) Select COUNT(*), [created], [research status] " & _
"from [gwc master list] " & _
"where [research status] = '" & status_var & "'" & _
" group by [research status], [created];"
Else
SQL = "insert into statussummary ([R_COUNT], [CREATED], [R_STATUS]) Select COUNT(*), [created], [research status] " & _
"from [gwc master list] " & _
"where [research status] = '" & status_var & "'" & _
" and [created] > #" & start_date & "# and created < #" & end_date & "#" & _
" group by [research status], [created];"
End If
Finally, fix your last statement:
rc = db.RecordsAffected
If rc = 0 Then
Debug.Print status & ": " & rc
SQL = "insert into statussummary ([R_COUNT], [R_STATUS]) values (" & rc & ", '" & status_var & "');"
db.Execute (SQL)
End If
End Sub

SQL syntax issue related to totalcount in combination with dates

Can any body help me with the following SQL statement?
What am I doing wrong here?
It is giving me no result however there should be some...
The desired result should be a list or errorsdetails with the total number of times it is in the database (mdb) based on the selected date-period.
PS sorry for my badly written English..
Many thanks
Koen
sSQL = "SELECT ErrorDetail, count(*) AS totalcount FROM tblErrors WHERE DisplayName = " & cbox_modules.Text & " AND ErrorDate BETWEEN #" & startdate & "# AND #" & enddate & "# GROUP BY ErrorDetail"
Assuming the "DisplayName" column is a string, ensure you surround it with apostrophes:
SELECT
ErrorDetail,
COUNT(*) AS totalcount
FROM tblErrors
WHERE DisplayName = '" & cbox_modules.Text & "' AND ErrorDate BETWEEN #" & startdate & "# AND #" & enddate & "#
GROUP BY ErrorDetail

SQL Sum statement very slow

new to SQL and having trouble with this code. It seems that the "SUM" function is just really slow. It times out if the date range is more than 5 days. I have to loop thru this 115 times and cover a date range of 180 days. Any ideas on what I can do to speed it up? The string times out in the SQL Enterprise Manager as well.
I've heard mention of using a "pivot" command, but don't know if that is the answer or how to implement it. TIA
strSQLRead = "SELECT SUM(BatchRecordDetail.BRD_Actual) AS LbsBatched, BatchRun.BAT_CoatingLBS AS CoatingLbs, " _
& "BatchRun.BAT_ID AS RunID " _
& "FROM BatchRun " _
& "INNER JOIN BatchRecordMaster ON BatchRun.BAT_HmiRunID = BatchRecordMaster.BRM_BatchRunID " _
& "AND BatchRun.BAT_Area = BatchRecordMaster.BRM_Area " _
& "INNER JOIN BatchRecordDetail ON BatchRecordMaster.BRM_Area = BatchRecordDetail.BRD_Area " _
& "AND BatchRecordMaster.BRM_HmiBatchID = BatchRecordDetail.BRD_BatchRecordID " _
& "WHERE (BatchRun.BAT_ExtruderEnd BETWEEN CONVERT(DATETIME, '" & Format(ToDate, "yyyy-MM-dd") & " 00:00:00', 102) " _
& "AND CONVERT(DATETIME, '" & Format(FromDate, "yyyy-MM-dd") & " 00:00:00', 102)) AND (BatchRun.BAT_RunComplete = 1) " _
& "AND BatchRun.BAT_FormulaCode = '" & sFormula(i) & "'" _
& "GROUP BY BatchRun.BAT_FormulaCode,BatchRun.BAT_ID, BatchRun.BAT_CoatingLBS " _
& "HAVING (BatchRun.BAT_CoatingLBS Is Not Null)"
Here is the string as trapped in code. Just wondering if anyone had any ideas. thx
SELECT Sum(batchrecorddetail.brd_actual) AS LbsBatched,
batchrun.bat_coatinglbs AS CoatingLbs,
batchrun.bat_id AS RunID
FROM batchrun
INNER JOIN batchrecordmaster
ON batchrun.bat_hmirunid = batchrecordmaster.brm_batchrunid
AND batchrun.bat_area = batchrecordmaster.brm_area
INNER JOIN batchrecorddetail
ON batchrecordmaster.brm_area = batchrecorddetail.brd_area
AND batchrecordmaster.brm_hmibatchid =
batchrecorddetail.brd_batchrecordid
WHERE ( batchrun.bat_extruderend BETWEEN
CONVERT(DATETIME, '2014-06-26 00:00:00', 102)
AND
CONVERT(DATETIME, '2014-06-26 00:00:00'
, 102) )
AND ( batchrun.bat_runcomplete = 1 )
AND batchrun.bat_formulacode = '3100007'
GROUP BY batchrun.bat_formulacode,
batchrun.bat_id,
batchrun.bat_coatinglbs
HAVING ( batchrun.bat_coatinglbs IS NOT NULL )
I can't post pics cause I don't have enough reputation points.
How would I display what else is needed to help answer the question?

Error when selecting between two dates from vb.net to sql

I have the code below
technician_sqlsource.SelectCommand = "Select analyst as Analyst, sample_description, RFA_number, convert(varchar(10), updated_date, 103)as updated_date, customer, po_number, total_charged from New_Analysis_Data where analyst = '" & FullName & "' and updated_date > '" & CDate(startdate.Text) & "'" & " and updated_date < '" & CDate(enddate.Text) & "'"
This basically passed through the sql command to the sql server and retrieves data between 2 dates. These dates come from 2 text boxes (start and end date). When I run this I get the error - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
If I remove & "'" & " and updated_date < '" & CDate(enddate.Text) & "'" then it will work, seems to be an issue with the enddate.
Use query parameters!
technician_sqlsource.SelectCommand = _
"SELECT analyst as Analyst, sample_description, RFA_number, " & _
" convert(varchar(10), updated_date, 103)as updated_date, " & _
" customer, po_number, total_charged " & _
" FROM New_Analysis_Data " & _
" WHERE analyst = #FullName " & _
" AND updated_date >= #StartDate AND updated_date < #EndDate"
With technician_sqlsource.SelectCommand.Parameters
.Add("#FullName", SqlDbType.VarChar,50).Value = FullName
.Add("#StartDate", SqlDbType.DateTime).Value = startdate.Text
.Add("#EndDate", SqlDbType.DateTime).Value = enddate.Text
End With
This also may or may not fix your problem with the end date. Even if it doesn't fix the problem, you should get a clearer error message... but most likely, you're not entering a valid date format in that textbox. Have you considered using a DatePicker control?
1st off you should use SqlParameters!!!
It is much safer and you will also get rid of the date conversion issue.
SqlCommand cmd=new SqlCommand();
cmd.CommandText = #"
Select analyst as Analyst,
sample_description,
RFA_number,
convert(varchar(10), updated_date, 103) as updated_date,
customer,
po_number,
total_charged
from New_Analysis_Data
where analyst = #analyst
and updated_date between #startdate and #enddate";
technician_sqlsource.SelectCommand = cmd;
technician_sqlsource.SelectCommand.Parameters.Add(new SqlParameter("#analyst", FullName));
technician_sqlsource.SelectCommand.Parameters.Add(new SqlParameter("#startdate",CDate(startdate.Text)));
technician_sqlsource.SelectCommand.Parameters.Add(new SqlParameter("#enddate", CDate(enddate.Text)));
If you want still in your old (unsafe) style .. you can try this ..
technician_sqlsource.SelectCommand = "Select analyst as Analyst, sample_description, RFA_number, convert(varchar(10), updated_date, 103)as updated_date, customer, po_number, total_charged from New_Analysis_Data where analyst = '" & FullName & "' and updated_date > #" & startdate.Text & "# and updated_date < #" & enddate.Text & "#"
But later you must use query parameters! .. to prevent SQL Injection !
try this:
technician_sqlsource.SelectCommand = "Select analyst as Analyst, sample_description, RFA_number, convert(varchar(10), updated_date, 103)as updated_date, customer, po_number, total_charged from New_Analysis_Data where analyst = '" & FullName & "' and updated_date > '" & CDate(startdate.Text) & "' and updated_date < '" & CDate(enddate.Text) & "'"