MS ACESS Error when accessing - ms-access

I am developing an enrolment system. But i am receiving this error: You tried to execute a query that does not include the specified expression..
I am using the following code:
Private Function RefreshAdvisoryList()
Dim vRS As New ADODB.Recordset
Dim sSQL As String
'clear list
txtsection.Clear
'On Error GoTo ReleaseAndExit
sSQL = "SELECT tblSection.SectionID, tblSection.SectionTitle, tblAdviser.SchoolYear, tblDepartment.DepartmentTitle, tblYearLevel.YearLevelTitle, tblAdviser.TeacherID" & _
" FROM (tblDepartment INNER JOIN (tblYearLevel INNER JOIN tblSection ON tblYearLevel.YearLevelID = tblSection.YearLevelID) ON tblDepartment.DepartmentID = tblSection.DepartmentID) INNER JOIN tblAdviser ON (tblSection.SectionID = tblAdviser.SectionID) AND (tblDepartment.DepartmentID = tblAdviser.DepartmentID)" & _
" GROUP BY tblSection.SectionID, tblSection.SectionTitle, tblAdviser.SchoolYear, tblDepartment.DepartmentTitle, tblYearLevel.YearLevelTitle, tblAdviser.TeacherID" & _
" HAVING (((tblTeacher.TeacherID)='" & curTeacher.TeacherID & "') AND tblSection.SchoolYear='" & Me.txtSchoolYear.Text & "')" & _
" ORDER BY tblAdviser.SchoolYear DESC;"
If ConnectRS(con, vRS, sSQL) = False Then
'fatal
'temp
MsgBox "Unable to connect Teacher's Advisory Recordset.", vbCritical
'GoTo ReleaseAndExit
End If
If AnyRecordExisted(vRS) = True Then
While vRS.EOF = False
txtsection.AddItem vRS!SectionTitle
vRS.MoveNext
Wend
End If
'Exit Function
'ReleaseAndExit:
' Set vRS = Nothing
End Function
Take a look at this screenshot:

The HAVING clause references these 2 fields:
tblTeacher.TeacherID
tblSection.SchoolYear
The SELECT field list includes:
tblAdviser.TeacherID
tblAdviser.SchoolYear
Change the query so that all references to TeacherID come from the same table. Do the same for SchoolYear.
BTW, tblTeacher is not even included among the query's data sources.
If possible, start an Access session and use the query designer to build this query. It will help you avoid this type of error. Once you have a query which works in Access, then adapt your code to produce the same working SQL statement.

Group by has to be used with a aggregate function so that combined result for a group can be retrieved, you have not used any aggregate function.
Refer - http://www.w3schools.com/sql/sql_groupby.asp
Remove group by from your query and add the having clause in the where clause.
Explain what type of data you are expecting so that we can help you in the query.

Related

Microsoft Access insert query

Access table Allowances_3_15_18 has 5 columns. I want to insert a calculated field from a form EmployeeSalary) into one of the columns Amount in the table.
Each value will link with the relevant primary ID's from the form and the table which are the same JobID. How do I do this in VBA?
I currently have done it in the afterUpdate event in the property sheet.
Private Sub ProjectedDollarAmount_AfterUpdate()
Dim strSQL As String
Dim ProjectedDollarAmount As Currency
strSQL = "INSERT INTO [Allowances_3_15_18] ([Amount]) VALUES (" & _
PrepareSQLNumber(Me.ProjectedDollarAmount) & ") WHERE JobID = " & _
PrepareSQLNumber(Me.JobID) & ";"
Call ExecuteMyCommand(strSQL)
End Sub
You need to get away from SQL concatenation and start using parameters.
Create a query with two parameters, the amount to be inserted and the JobId. The query's SQL should be something like this:
PARAMETERS [prmAmount] Currency, [prmJobId] Long;
UPDATE [Allowances_3_15_18] SET [Amount] = [prmAmount]
WHERE JobID = [prmJobId];
Then in code, simply pass the parameter values and execute the above query:
Sub Add()
With CurrentDb().QueryDefs("qryName")
.Parameters("[prmAmount]").Value = PrepareSQLNumber(Me.ProjectedDollarAmount)
.Parameters("[prmJobId]").Value = PrepareSQLNumber(Me.JobID)
.Execute dbFailOnError
End With
End Sub
You need to change the qryName to the actual name of the query.
You can read more about parameter queries here.

Run-time error '3061' Too few parameters. Expected 1

Keep getting a run-time error 3061 which the following script in Acces. Debugger reports a problem with last line but for the life of me I cannot see what the issue is. Any assistance greatly appreciated.
Dim db As Database
Dim salers As DAO.Recordset 'Sale
Set db = CurrentDb
Dim saleQuery As String
saleQuery = "SELECT * FROM Sales WHERE salesID = " & Me.saleID.Value & ";"
Set salers = db.OpenRecordset(saleQuery)
This error almost always means something is miss-spelled, or doesn't exist. So, ensure that Sales and salesID exist and are spelled properly in the query.
If that is OK, look at Me.saleID.Value. If this is a string, the query will have enclose the value in quotes:
saleQuery = "SELECT * FROM Sales WHERE salesID = '" & Me.saleID.Value & "';"
Note the ' around the saleID value.

DBEngine(0)(0).Execute DELETE to complete before APPEND

I have two statements in VBA. Here is a fragment of code:
'delete records from tbl_PLAN_data
strErr = "1a"
strSQL = "DELETE tbl_PLAN_data.*"
strSQL = strSQL & " FROM tbl_PLAN_data;"
DBEngine(0)(0).Execute strSQL, dbFailOnError + dbSeeChanges
DoEvents
strErr = "2a"
'append records to tbl_PLAN_data
DBEngine(0)(0).Execute "qryAppPLAN", dbFailOnError + dbSeeChanges
DoEvents
SQL string of qryAppPLAN:
INSERT INTO tbl_PLAN_data ( ID, Qty, QtyPln, QtyAct, ProdT, TmStamp, TID, Wks, vol, v4, v4k, DataPln, Shift, DataPlnShift, GRD, Wk, Wkd, GRDLdKf, KFig )
SELECT tbl_OrderDetailsSub.OrderDetailsSubID, [Quantity]-Sum(Nz([Qtyact],0)*IIf([np]=0,1,-1)) AS Qty, tbl_OrderDetails.Quantity, Sum(Nz([Qtyact],0)*IIf([np]=0,1,-1)) AS QA, Sum(tbl_OrderDetailsSub.PT) AS SumOfPT, Now() AS TmStamp, tbl_OrderDetailsSub.TID, tbl_Tooling.WksID, tbl_OrderDetailsSub.Volume, tbl_OrderDetailsSub.Vol4, tbl_OrderDetailsSub.Vol4K, tbl_OrderDetailsSub.DataPln, tbl_OrderDetailsSub.Shift, [datapln] & "-" & [shift] AS datshift, IIf(InStr([oprdetails],"G")>0 Or InStr([oprdetails],"Hs")>0 And InStr([oprdetails],"GL")=0,1,0) AS GRD, DatePart("ww",[DataPln],0,2) AS w, DatePart("w",[DataPln],0,2) AS wd, tbl_OrderDetailsSub.TblLoadKf, Nz([Koef],1) AS Expr1
FROM ((tbl_Order INNER JOIN (tbl_OrderDetails INNER JOIN tbl_OrderDetailsSub ON tbl_OrderDetails.[OrderDetailsID] = tbl_OrderDetailsSub.[OrderDetailsID]) ON tbl_Order.[OrderID] = tbl_OrderDetails.[OrderID]) LEFT JOIN tbl_ProdAct ON tbl_OrderDetailsSub.[OrderDetailsSubID] = tbl_ProdAct.ODSubID) INNER JOIN tbl_Tooling ON tbl_OrderDetailsSub.TID = tbl_Tooling.TID
WHERE (((tbl_Order.ProdTypeID)<>"S" Or (tbl_Order.ProdTypeID) Is Null) AND ((tbl_Order.CancelledDate) Is Null) AND ((tbl_Order.RefusingReason) Is Null) AND ((Right(CStr(Nz([tbl_Order]![ProcessedDate],"12:00:00")),8))="12:00:00") AND ((tbl_Order.OrderType)<>"Pasiûlymas") AND ((tbl_Order.ShippedDate) Is Null))
GROUP BY tbl_OrderDetailsSub.OrderDetailsSubID, tbl_OrderDetails.Quantity, tbl_OrderDetailsSub.TID, tbl_Tooling.WksID, tbl_OrderDetailsSub.Volume, tbl_OrderDetailsSub.Vol4, tbl_OrderDetailsSub.Vol4K, tbl_OrderDetailsSub.DataPln, tbl_OrderDetailsSub.Shift, [datapln] & "-" & [shift], IIf(InStr([oprdetails],"G")>0 Or InStr([oprdetails],"Hs")>0 And InStr([oprdetails],"GL")=0,1,0), DatePart("ww",[DataPln],0,2), DatePart("w",[DataPln],0,2), tbl_OrderDetailsSub.TblLoadKf, Nz([Koef],1), tbl_OrderDetails.Quantity
HAVING ((([Quantity]-Sum(Nz([Qtyact],0)*IIf([np]=0,1,-1)))>0) AND ((tbl_OrderDetailsSub.DataPln)>Date()-30))
ORDER BY tbl_OrderDetailsSub.DataPln;
Sometimes at second execute statement I get error "Record is deleted". It seems logic when I append records after deletion. But how to force VBA to wait till delete statement completes?
I would suggest you create a Database Object and execute on that object rather than using the DBEngine(0)(0), as when you use this, you are not only performing an expensive operation of creating a new instance of the Database, you are also trying to query the table which you just modified (deleted), so you might have a small glitch.
Dim dbObj As DAO.Database
Set dbObj = CurrentDB()
'delete records from tbl_PLAN_data
strErr = "1a"
strSQL = "DELETE tbl_PLAN_data.* FROM tbl_PLAN_data;"
dbObj.Execute strSQL, dbFailOnError + dbSeeChanges
'Optional
'DoEvents
strErr = "2a"
'append records to tbl_PLAN_data
dbObj.Execute "qryAppPLAN", dbFailOnError + dbSeeChanges
By creating a Database Object, you are making sure the operations are made against the "active" object on which you also made a modification, so would return you the right information. DoEvents might not even be required. I have added it, if you feel it is still causing problems introduce it again and see if it makes any difference.
Good Luck !

Merge 2 fields and insert into table

hi i am trying to insert value into my output table 
in my Input table have 
profit  extra 
10         20 
when i insert into my output table it should get concatenated as 
cost 
1020 
sub test()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Set db = CurrentDb
db. execut "Insert into OUTPUT_TBL (DESCRIPTION,COST,DEBIT,CREDIT) " & _
" SELECT INPUT.DESCRIPTION,((INPUT.PROFIT)+(INPUT.EXTRA)) AS COST," & _
" IIF(EXTERNAL.SOLUTION='DEBIT',(AMOUNT),0) as DEBIT, " & _
" IIF(EXTERNAL.SOLUTION='CREDIT',(AMOUNT),0) AS CREDIT " & _
" FROM INPUT , EXTERNAL"
db.close
end test
when i try to run it i am getting error as  run time error 3075
Couple issues - noticed a typo, it should be db.execute "" not db.execut
Also, for string concatenation use & in Access SQL. 3075 means you used a bad operator.
Another thing, You may also need to add a JOIN to the SQL.
For example, to get you on the right track:
db.execute "Insert into OUTPUT_TBL (DESCRIPTION,COST,DEBIT,CREDIT) SELECT INPUT.DESCRIPTION,((INPUT.PROFIT)&""&(INPUT.EXTRA)) AS COST,IIF(EXTERNAL.SOLUTION='DEBIT',(AMOUNT),0) as DEBIT, IIF(EXTERNAL.SOLUTION='CREDIT',(AMOUNT),0) AS CREDIT from INPUT JOIN EXTERNAL ON INPUT.KEY=EXTERNAL.KEY"

ODBC select statement to get a boolean

I'm trying to check whether a Username and Password exist in my MySQL database and if so I need to return true, otherwise false. This is what I have atm:
myconn.Open()
Dim selectSQL As String = "SELECT *
FROM member
WHERE Username = " & objMember.Username & "
AND Password= " & objMember.Password
Dim cmd As New OdbcCommand(selectSQL, myconn)
cmd.ExecuteNonQuery()
If cmd.Parameters.Count = 1 Then
Return True
Else
Return False
End If
myconn.Close()
myconn.Dispose()
All I get is 0, even though the Username and Password exist! Or perhaps I'm wrong with my coding?
SOLUTION
myconn.Open()
Dim count As Integer = 0
Dim selectSQL As String = "SELECT COUNT(*)
FROM member
WHERE Username = ?
AND Password= ?"
Dim cmd As New OdbcCommand(selectSQL, myconn)
cmd.Parameters.AddWithValue("LidLoginnaam", objLid.LidLoginnaam)
cmd.Parameters.AddWithValue("LidWachtwoord", objLid.LidWachtwoord)
count = Convert.ToInt32(cmd.ExecuteScalar())
If count = 1 Then
Return True
Else
Return False
End If
myconn.Close()
myconn.Dispose()
Do not use string concatenation to build your SQL queries, use parameters instead.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcparameter.aspx
Dim count as Integer = 0
Try
Dim sql As String = "SELECT COUNT(*) FROM member WHERE Username = #username AND Password = #password"
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#username", objMember.Username)
cmd.Parameters.AddWithValue("#password", objMember.Password)
count = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return (count > 0)
If you don't use the data retrieved from your query, then just use ExecuteScalar to get the number of records that matched your Username and Password.
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbccommand.executescalar.aspx
This basically returns TRUE if count > 0 (meaning there is a record that matched the Username and Password).
Also check out the distinction between the different command execution methods here: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand(v=vs.71).aspx. You are using ExecuteNonQuery for retrieving records which is incorrect for this purpose.
Hope this helps.
Ignoring the SQL Injection risks, strings in SQL need to be within single quotes:
Dim selectSQL As String = "SELECT m.*
FROM MEMBER m
WHERE m.username = '" & objMember.Username & "'
AND m.password = '" & objMember.Password & "' "
From a performance perspective, if you aren't interested in the contents of the query then don't return more information than you need to:
Dim selectSQL As String = "SELECT 1
FROM MEMBER m
WHERE m.username = '" & objMember.Username & "'
AND m.password = '" & objMember.Password & "' "
The query will be faster -- if any of the MEMBER columns are BLOB, you could be waiting for a while.
I think you're missing the single quotation in the query:
Dim selectSQL As String = "SELECT *
FROM member
WHERE Username = '" & objMember.Username & "'
AND Password= '" & objMember.Password & "'"
OdbcCommand's Parameter property is used for accessing the collection of parameters to be used when executing a query (more info). It doesn't help you find out how many rows are contained in the query's result set.
If your only concern is determining whether or not the requested member is in the database, change the start of your query to SELECT COUNT(*) FROM..... This revised query will return a single value indicating how many records match your query's criteria.
Execute this query by calling ExecuteScalar. The return value of this method will be the value returned by the above query--the number of rows matching your query's criteria. If the value equals zero, you know that no matching member exists in the database. Use this value instead of "cmd.Parameters.Count" in your "if" statement.
Hope this helps,
Ben