Calculated query on multivalued fields in access - sql

I have a table 'Contacts' which has a multivalued field 'Department'. I have another table 'Outreach' and it has a field 'partner org'. I have a query which combines 'Contacts.Department' and 'outreach.[partner org]' into one field joining the two tables using an outer join on fullname field which is common in both tables.
The SQL statement I have to combine the two fields is
Contacts.Department & ";" & Outreach.[Partner Org] AS [Dept/Partner Org]
If I run this query, I get the error saying
The multivalued field 'Contacts.Department' is not valid in the expression 'Contacts.Department & " " & Outreach.[Partner Org] AS [Dept/Partner Org]'
If I add the '.Value' to the multivalued field, I get multiple rows.
Contacts.Department.Value & " " & Outreach.[Partner Org] AS [Dept/Partner Org]
I want the output to have the multivalued valued field contents followed by a ';' and the partner org name all in the same cell.
Please can someone tell me to how to get this.
Thank You.

I've come up against a similar problem with these useful (from the end-users perspective) but irritating (from the perspective of those analysing) fields.
I came up with a workaround, using a form, that I think solves your problem. I added a pseudo-departments text field to the table, applied slightly modified code from the fourth post to the relevant field(s) "AfterUpdate" events as & when they change (I pass the current record & the SQL string only summarises that record).
Dim db As Database, _
rst As Recordset, _
strSQL As String
Me.Refresh
Set db = CurrentDb
strSQL = "Select PseudoDepartment from YOURTABLE where UNIQUEIDNO = " & Me.UNIQUEIDNO & ";"
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
With rst
If .RecordCount > 0 Then
.MoveFirst
.Edit
!PseudoDepartment = MakeList(Me.UNIQUEIDNO)
.Update
End If
End With
To initialise the pseudo-departments field, one could loop through all records one by one to generate the contents. One can then query the data normally and get the results in the form you indicated.
HTH.

Related

MS Access SQL - Update field in one table with a count from another table

I have a table called 'FilesUploaded' which has a summary of all files uploaded to my access DB. I want to add a field in here that contains the count of all errors from another table.
My FilesUploaded table contains a field called 'FileName' which has
the full name of the file.
I want to get a count of all records in table1 where the 'ValidityCheck' field contains 'Error'. Table1 also contains a field called 'Name_of_Report' which has the file name which will match back to the FilesUploaded table.
The 'vFileName' variable will contain what is in both the 'Filename' field and the 'Name_of_Report' field
The below is the code I have tried using, but it says this type of join is not allowed and I have no idea what other way I can achieve this.
Call RunSQL("UPDATE FilesUploaded " & _
"LEFT JOIN (SELECT table1.Name_of_Report, Sum(IIf([table1].[ValidityCheck] Like '*Error*',1,0)) AS ErrorCount FROM table1 GROUP BY table1.Name_of_Report) AS temp on temp.Name_of_Report = FilesUploaded.FileName " & _
"SET " & _
"FilesUploaded.[ErrorCount] = temp.ErrorCount " & _
"WHERE FilesUploaded.[FileName] = '" & vFileName & "' ")
Does anybody know a different way can update the FilesUploaded table with a count of the ValidityCheck field from the Table1 table?
In MS Access, UPDATE...JOIN requires its analogous SELECT...JOIN to be updateable. Aggregate queries using SUM are not updateable queries. Therefore, consider domain functions like DSum.
Additionally, consider a stored query and call it in VBA with parameterization via QueryDefs. Do note the use of ALIKE to use % for wildcards in case you need to run query outside of the MS Access GUI such as in ODBC or OLEDB connections where * is not recognized.
SQL (save as a stored query)
PARAMETERS paramFileName TEXT;
UPDATE FilesUploaded f
SET f.[ErrorCount] = DSUM("*", "table1",
"[ValidityCheck] ALIKE '%Error%' AND [Name_of_Report]='" & f.[FileName] & "'")
WHERE f.[FileName] = [paramFileName];
VBA (run query without string concatenation)
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
qdef![paramFileName] = vFileName ' BIND PARAM VALUE
qdef.Execute ' RUN ACTION QUERY
Set qdef = Nothing

Displaying a field associated with a max date value record

I am working on an MS Access database and have been trying to get an unbound field on a main navigation form to display the LastUserChange that is associated with the record that was last updated.
I have used DMax() to identify the record that was most recently updated, but I can't seem to get the user ID associated with that record to display. I have a field in the table with the date timestamp that stores the user ID with it, so the data is saved in the same table. The code that I have been working on is as follows:
Private Sub Form_Load()
Dim strSQL As String
strSQL = "SELECT tblstatusupdate.LastUserChange" & _
"FROM tblstatusupdate " & _
"WHERE tblstatusupdate.LastChangeDate = DMax("LastChangeDate", "tblStatusUpdate")"
DoCmd.RunSQL strSQL
Me.LastUpdateBy = strSQL
End Sub
The code that I used to get the date of the most recently updated record is:
= DMax("LastChangeDate", "tblStatusUpdate")
Can someone please help me?
Often a mistake of new users in MS Access, DoCmd.RunSQL is reserved for action queries (i.e., INSERT, DELETE, UPDATE, ALTER, CREATE) and not SELECT queries that return a resultset.
However, for your needs consider running nested domain functions in VBA without any SQL calls. DLookUp looks up user with the criteria that its change date matches the max value of table using Dmax. Date literals must be enclosed with # characters and not quotes.
Me.LastUpdatedBy = DLookUp("LastUserChange", "tblStatusUpdate", "LastChangeDate = #" _
& DMax("LastChangeDate", "tblStatusUpdate") & "#")

count the number of rows in sql query result using access vba

I am trying to count the number of rows in sql query result using access 2007 vba.
What I have is a text box named AGN when a user put value on it check for this value then it bring back MsgBox if the the value is already inserted. What I try to do is :
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT agencies.[agency no] FROM agencies WHERE agencies.[agency no]= " &Me.AGN.Text
Set rs = db.OpenRecordset(strSQL)
If rs.Fields.Count > 1 Then
MsgBox "this value is already here "
End If
Set rs = Nothing
When I insert any value on the textbox I got run time error 3061 (too few parameters)
The "too few parameters" error message generally means there is something in your SQL statement which Access doesn't recognize as a field, table, function or SQL keyword. In this case, it could happen if [agency no] is text rather than numeric data type. If that is the case, enclose the value of AGN with quotes when you build the SQL statement. (Or you could use a parameter query to avoid the need to quote the text value.)
strSQL = "SELECT a.[agency no] FROM agencies AS a" & vbCrLf & _
"WHERE a.[agency no]= '" & Me.AGN.Value & "'"
Debug.Print strSQL
In case of trouble, go to the Immediate window and copy the output from Debug.Print. Then you can create a new query in the Access query designer, switch to SQL View and paste in the statement text for testing.
Once your SELECT is working, you can check whether or not the recordset is empty. When it is empty both its BOF and EOF properties are true. So to detect when it is not empty, check for Not (BOF And EOF) ...
With rs
If Not (.BOF And .EOF) Then
MsgBox "this value is already here "
End If
End With
However you don't actually need to open a recordset to determine whether a matching row exists. You can check the value returned by a DCount expression.
Dim lngRows As Long
lngRows = DCount("*", "agencies", "[agency no]='" & Me.AGN.Value & "'")
If lngRows > 0 Then
MsgBox "this value is already here "
End If
Notes:
I used AGN.Value instead of AGN.Text because the .Text property is only accessible when the control has focus. But I don't know where you're using that checking code, so unsure which is the proper choice for you.
Notice the similarities between the SELECT query and the DCount options. It's often easy to translate between the two.

Access query updatable fields with group by

I want to create a split form based on a query where the fields are all grouped. The split form will not let me update the records because they are grouped. For instance let's say 10 records all had the same data in a field called "Company Name". Is there any way to make the query updatable such that when I change the data for "Company Name" on the grouped entry it will change for all of the records that are grouped?
Thanks
it is definitively not possible to update a grouped query.
The reason is, that a grouped query cannot contain the key (if you include it, you have no more a grouping, as the key is unique ...)
So Access has no clue, what is grouped and which records should be updated
What you have to do is:
create a form based on the query
add an event "on double-click" to the field you want to change
program a dialog to ask for new value
fire an sql to update
here a sample for steps 2-4
Private Sub DOK_DokumentNr_DblClick(Cancel As Integer)
Dim newvalue As Variant
Dim sSQL As String
newvalue = InputBox("enter new value", "DOC-Number", Me!DOK_DokumentNr.OldValue)
If newvalue <> Me!DOK_DokumentNr.OldValue Then
sSQL = "UPDATE T_Dokument SET DOK_DokumentNr = '" & newvalue & "' "
sSQL = sSQL & "WHERE DOK_DokumentNr = '" & Me!DOK_DokumentNr.OldValue & "'"
DoCmd.SetWarnings False ' to prevent the standard message for modifying data
DoCmd.RunSQL sSQL
DoCmd.SetWarnings True ' reset warnings to default
End If
End Sub

Comparing a virtual child's filters to parent table

I haven't a clue as to how to do this. I'm using Access 2007, and coding in VBA and SQL.
Table A has Data, accounts and amounts. Users can use form B to access subsets of the data in A, say, all the rows with amounts between $50 and $100.
When the user is looking at a row, I need to know if there are any other rows with the same account that are excluded from their view. In other words, I need to know if there are rows visible in the parent that aren't visible in the child.
I think a solution is to determine what filters are active on their view, and then I can use dcount to compare. I don't know how to get at the filters that are active in their view, though. And there may be an easier way - I am out of my depth here.
Let us assume that TableA has a primary key ID. Using the current event for the FormB:
Dim rs AS DAO.Recordset
dAmt = Me.Amount
sAcc = Me.Account
''Get a list of visible IDs
With Me.RecordsetClone
.MoveFirst
Do While Not .EOF
If !Amount=dAmt And !Account=sAcc Then
sIDs = sIDs & "," & .ID
End If
.MoveNext
Loop
End with
''Other IDs
sSQL = "SELECT * FROM TableA "
& "WHERE Amount = " & dAmt _
& "Account = '" & sAcc _
& "' ID Not In (" & Mid(sIDs,2) & ")"
CurrentDB.CreateQueryDef("NewQ",sSQL")
Docmd.OpenQuery NewQ
The above is untested, and as it stands, will only run once, if it runs at all, because a new query is created, rather than an existing query being edited.