I have this SQL query
cmd.CommandText = "SELECT [tblStudent]![LastName] & ', ' & [tblStudent]![FirstName] & ' ' & [tblStudent]![MiddleName] AS FullName," & _
" tblGrade.FirstGrading, tblGrade.SecondGrading, tblGrade.ThirdGrading, tblGrade.FourthGrading," & _
" Avg(b.GradeValue) AS AverageGrade" & _
" FROM ((((tblGrade INNER JOIN tblEnrolment ON tblGrade.EnrolmentID=tblEnrolment.EnrolmentID)" & _
" INNER JOIN tblStudent ON tblStudent.StudentID=tblEnrolment.StudentID)" & _
" INNER JOIN tblSubjectOffering ON tblSubjectOffering.SubjectOfferingID=tblGrade.SubjectOfferingID)" & _
" INNER JOIN tblSubject ON tblSubject.SubjectID=tblSubjectOffering.SubjectID)" & _
" INNER JOIN tblSection ON tblSection.SectionID=tblSubjectOffering.SectionID" & _
" WHERE tblSection.SectionTitle='" & s(0) & "' AND tblSubject.SubjectID='" + s2(0) + "'" & _
" GROUP BY [tblStudent]![LastName] & ', ' & [tblStudent]![FirstName] & ' ' & [tblStudent]![MiddleName], tblGrade.FirstGrading, tblGrade.SecondGrading, tblGrade.ThirdGrading, tblGrade.FourthGrading" & _
" ORDER BY [tblStudent]![LastName] & ', ' & [tblStudent]![FirstName] & ' ' & [tblStudent]![MiddleName]"
And this code gives me a runtime error "No value for one or more required parameters".
My hunch is Access thinks b.GradeValue is a parameter because there is no table name or alias for b:
Avg(b.GradeValue) AS AverageGrade
I suggest you Debug.Print the completed SELECT statement, or write it to a text file, then test it as a new query in the Access query designer. When it asks you to supply the parameter value, it also shows you the "name" of whatever it thinks is the parameter.
Very difficult to offer suggestions with only a SQL statement, out of context with your other code and objects.
As it stands, I see two main potential problems. First is that you have Avg(b.GradeValue) but there is no reference to the b table elsewhere in the command. For this, you would need to remove the b or make sure the reference is valid.
Second, you have two variables, s() and s2() that could be returning invalid or null data. You may want to debug this step and check the values each of these holds before letting it proceed, then fix the problem in the other part of your code if one is bad.
Related
I have the following and getting the error in INSERT INTO statement. I've done a debug.print and pasted back into SSMS and it works just fine so I'm really stumped. The syntax looks fine to me but I know sometimes going from straight SQL to VBA SQL can be tricky. I had a feeling it was the EXISTS section and I took that out and made the appropriate edits and still got the error msg. Any suggetions?
sqlstr = "INSERT INTO [database.[dbo].[table]" & _
"(" & _
"User_name" & _
",Client_Id" & _
",Client_Name" & _
",UserAccess" & _
",UserId" & _
")" & _
"SELECT " & _
"User_name = '" & UserName & "'" & _
",Client_Id = " & Me.ClientList.ItemData(ClientID) & "" & _
",Client_Name = '" & Me.ClientList.Column(1, ClientID) & "'" & _
",UserAccess = 0" & _
",UserId = " & UserId & "" & _
" WHERE NOT EXISTS (SELECT 1 FROM [database].[dbo].[table] where UserID = " & UserId & " and Client_Id = " & Me.ClientList.ItemData(ClientID) & ")"
Access SQL != T-SQL.
You either need to run this SQL string as a Pass-Through query, then it's the same as running it in SSMS.
Or translate it into Access SQL.
At the very most you must change the table names into the names of the linked tables in Access (which certainly aren't [database].[dbo].[table])
If you need more help with option 2, please post the formatted result of Debug.Print sqlstr
I trying to create Add,update,Delete operation on MS Access form.I found this code on internet where Insert and update is happening on the same button. I am not getting what is exactly happening in below line and how it's identifying it is for update or insert.
Not getting following line : = Me.txtid.Tag & "" = ""
Please find below code which works perfect as per requirement.
'When we click on button Add there are two options
'1. for insert
'2. for update
If Me.txtid.Tag & "" = "" Then
' this is for insert new
' add data in table
CurrentDb.Execute "insert into student(stdid,stdname,gender,phone,address)" & _
" values(" & Me.txtid & ",' " & Me.txtname & " ',' " & Me.cmbgender & " ','" & _
Me.txtphone & "', '" & Me.txtaddress & "')"
'refresh data in list on form
subform_student.Form.Requery
Else
CurrentDb.Execute "UPDATE student " & _
" set stdid = " & Me.txtid & _
", stdname = '" & Me.txtname & "' " & _
", gender = '" & Me.cmbgender & " ' " & _
", phone = ' " & Me.txtphone & " ' " & _
", address = ' " & Me.txtphone & " ' " & _
" WHERE stdid = " & Me.txtid.Tag
End If
The .Tag property is a general-purpose string property of every form and control object in VBA/VB6. It is provided as a place for developers to "put stuff" to support the operation of their applications.
The original code from which you copied your sample must have written a value to Me.txtid.Tag when the record was loaded (e.g., perhaps in the form's Current event) to indicate whether the record is an existing record or a new record (empty="new", non-empty="existing"). The line
If Me.txtid.Tag & "" = "" Then
simply checks to see if the .Tag property is empty, and then performs the INSERT or UPDATE accordingly.
BTW, re:
below code which works perfect as per requirement
No, it doesn't. Try adding a record where [stdname] is Tam O'Shanter and see for yourself. You should ditch the dynamic SQL and use one of
a bound form (as Gustav suggests),
a parameterized query, or
a recordset update.
Forget/remove all this code and bind the form to table Student to make this all happen automatically.
If a bound form is not familiar to you, browse for a tutorial for "Beginning with Microsoft Access" or the like.
I'm totally stumped at this one.. Skip to bottom to read problem
Here's my listbox (DocumentList) that takes the fields from the 'Documents' Table:
Document Name Status Notes Consultation Notes
Doc A Started Document Started Aim to process on 05/05/16
Doc B Processing Document Processing Aim to complete on 05/05/16
Doc C Complete Complete on 01/01/16 N/A
I have the onclick event set so that when you select a row from the listbox, it assigns each field to a text box/Combobox.
textboxes/Combobox names:
txtDocument
StatusCombo
txtNotes
txtConNotes
code for each one in 'DocumentList' click event:
Private Sub DocumentList_Click()
txtDocument = DocumentList.Column(0)
StatusCombo = DocumentList.Column(1)
txtNotes = DocumentList.Column(2)
txtConNotes = DocumentList.Column(3)
After the data is assigned to them from the listbox, you can edit it. I have an update button, which when pressed will replace everything in the database with everything in the textboxes/Combobox. The listbox is then re-queried and displays the updated data.
Heres the code for my update button:
Private Sub UpdateButton_Click()
CurrentDb.Execute "UPDATE [Documents] " & _
"SET [Document Name] = '" & Me.txtDocument & "'" & _
", [Status] = '" & StatusCombo.Value & "'" & _
", [Notes] = '" & Me.txtNotes & "'" & _
", [Consultation Notes] = '" & Me.txtConNotes & "'" & _
"WHERE [Document Name] = '" & DocumentList.Column(0) & "'" & _
"AND [Status] = '" & DocumentList.Column(1) & "'" & _
"AND [Notes] = '" & DocumentList.Column(2) & "'" & _
"AND [Consultation Notes] = '" & DocumentList.Column(3) & "'"
DocumentList.Requery
End Sub
My problem is the code only works on 2 out of 3 of the documents. All aspects of the code work, but only on some of the documents. This doesn't make any sense to me. At first I thought it may be a spelling error, but even if it was, none of the documents should get updated.. But some of them do, 1 doesn't..
Any ideas why this code updates some documents, but doesn't update others?
Nothing is updated when [Documents].[Consultation Notes] is Null, because the WHERE clause targets an empty string instead ... "'" & DocumentList.Column(3) & "'" ... so no matching row is found.
The task would be simpler if you add an autonumber primary key, ID, to the [Documents] table. Then include ID in the list box Row Source, and use that value in the WHERE clause to target the row you want to update. (The ID column doesn't have to be visible in the list box; you can set its column width property to zero.)
Then your WHERE clause can be much simpler: just target the record whose ID matches the ID column value of the selected list box row. That strategy would also avoid the complication of "Null is never equal to anything, not even another Null".
Finally, consider a parameter query for the UPDATE instead of concatenating values into a string variable.
I have form where user can search the database by worker ID , name/surname, job.
I want to make possible all possible variations e.g. ID+name/surname+job or ID+job, or name/surname etc.
I have done all except combinations with ID's. Searching only by ID works, but combinations don't as I do not know what is the correct syntax. I have tried many, many ways to do this, but with no result.
Here is searching only by ID:
DoCmd.OpenForm "DarbiniekiSearchResults", acFormDS
Forms!DarbiniekiSearchResults.RecordSource = "" _
& "SELECT * " _
& "FROM Darbinieks " _
& "WHERE ID_darbinieks=" & Forms!SearchDarbinieki!darbIDsearch
And here is what I am trying to do: ID+job:
DoCmd.OpenForm "DarbiniekiSearchResults", acFormDS
Forms!DarbiniekiSearchResults.RecordSource = "" _
& "SELECT * " _
& "FROM Darbinieks " _
& "WHERE ID_darbinieks= & Forms!SearchDarbinieki!darbIDsearch OR amats_darb= '" & Forms!SearchDarbinieki!darbAmatsSearch & "'"
And the error is: http://i.stack.imgur.com/NA2bi.png
I have a data entry form (Access 2007) which is designed to find out if the captured animal already has an existing WHno. Unfortunately, the data is messy and these is not a single unique identifier so several tests must be performed to narrow the search.
The animal could have 1 to 10 different pieces of information which will help identify the animal’s existence in the database. (The script only tests for about half of them thus far) I was thinking the best way to do this would to be to “build” a DCount and/or SQL statement based on which fields the user selects. I hope test to see if a particular text field box (unbound) has been filled out, and if yes, concatenate that section of code to the DCount/SQL statement, then move on to the next text field box to test.
Once the statement has been completely built, I want to test to see how many records have been counted/selected. If one record has been selected, I want to display the results in FormA. If 2 or more records are found, I want to display the records in a multi-listing form (FormB) from which the user can select the correct animal based on additional information not tested but displayed in FormB. If zero records are found, I want to create a new record with the data entered into the form updated into the table.
The hurdle I am struggling with now is building the DCount statements. I keep getting syntax errors . I do not know how to put this together piecemeal when the function bombs out because the syntax is incomplete (which it will be until I finish “building” it.)
I know the data is a mess. The scene out in the field is chaotic, different people gather different kinds of information, and not all the data that should be entered on the paper forms get filled out completely - if at all. The data gathering procedures are unlikely to change anytime soon.
Ideas? A different but easier approach idea is also welcome. New to this and not sure of all my programming options.
Also, how long can this statement be before it bombs out?
Code so far:
Private Sub GenerateWHno_Click()
Dim rs As DAO.Recordset
If IsNull(Forms!F_HotelEntry!txtSpecies) Or (Forms!F_HotelEntry!txtSpecies) = "" Then
MsgBox "Species is a required field. Please enter a species"
Exit Sub
End If
MsgBox txtSpecies
' Each line of code below indicates a data entry field(s) that needs testing and appended to SpeciesCount if "true". The first line is unchanging and is declared upfront.
'SpeciesCount = DCount("[Species]", "AnimalInfo", "(nz([Status])= '' OR [Status] = 'Alive' OR [Status] = 'Unknown') AND ([Species]= '" & txtSpecies & "')" _
' & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
' & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
' & "AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
' & "AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
' & "")
'If txtL_ET_Color Is Not Null Or txtL_ET_No Is Not Null Then
'LET1 = & "AND (((nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & nz(txtL_ET_No1) & "')" _
'Species Count = SpeciesCount & LET1
'End If
'If txtR_ET_Color Is Not Null Or txtR_ET_No Is Not Null Then
'RET1 = & "AND (((nz([R_ET_Color1])= '" & Nz(txtR_ET_Color1) & "' AND nz([R_ET_No1])= '" & nz(txtR_ET_No1) & "')" _
'Species Count = SpeciesCount & RET1
'End If
'If txtL_ET_No2 Is Not Null Then
'LET2 = AND nz([L_ET_No2])= '" & nz(txtL_ET_No2) & "')" _
'Species Count = SpeciesCount & LET2
'End If
'If txtR_ET_No2 Is Not Null Then
'RET2 = AND nz([R_ET_No2])= '" & nz(txtR_ET_No2) & "')" _
'Species Count = SpeciesCount & RET2
'End If
'There are about 4 more options/fields to add to the script but you get the idea.
'Thus: If user selected Species, and filled out L_ET_Color1 and/or L_ET_No1, the final concatenation (DCount statement)would look like this:
SpeciesCount = DCount("[Species]", "AnimalInfo", "([Status]= 'Alive' OR [Status] = 'Unknown' OR nz([Status]) = '') AND [Species]= '" & txtSpecies & "' AND (nz([L_ET_Color1])= '" & Nz(txtL_ET_Color1) & "' AND nz([L_ET_No1])= '" & Nz(txtL_ET_No1) & "')")
If SpeciesCount > 1 Then
MsgBox SpeciesCount & " Greater than 1. Please select correct animal"
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as multilisting to select from
ElseIf SpeciesCount = 0 Then
MsgBox "You need a new WHno"
WHno = Nz(DMax("WHno", "AnimalInfo")) + 1
MsgBox WHno
Set rs = CurrentDb.OpenRecordset("AnimalInfo")
rs.AddNew
rs!WHno = WHno
rs!Species = txtSpecies
rs!L_ET_Color1 = txtL_ET_Color1
rs!L_ET_No1 = txtL_ET_No1
rs.Update
rs.Close
Else
'Create SQL statement that mimics DCount statement and display all fields from AnimalInfo table as single listing in a form.
MsgBox "You're WHno is " & WHno & " Is this the correct WHno?"
End If
Forms!F_HotelEntry!txtSpecies = ""
Forms!F_HotelEntry!txtL_ET_Color1 = ""
Forms!F_HotelEntry!txtL_ET_No1 = ""
End Sub
I would suggest to first compose the condition into a string variable. There you can print its content via Debug.Print and see what the problem might be.
If you cannot spot the problem via inspection alone, paste the generated string to the Sql view of a proper query and see if Access gives you helpful information on switching to design view.